使用Object.create()和使用赋值运算符有什么区别? [英] What is the difference between using Object.create() and using assignment operator?

查看:192
本文介绍了使用Object.create()和使用赋值运算符有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是一些示例。

// case 1:
var obj1 = {msg : 'Hello'};
var obj2 = obj1;
obj2.msg = "Hi!"; //overwrites
alert(obj1.msg); //=>'Hi!'

// case 2:
var obj1 = {msg : 'Hello'};
var obj2 = Object.create(obj1);
obj2.msg = "Hi!"; //does not overwrite
alert(obj1.msg); //=>'Hello'

// case 3:
var obj1 = {data: { msg : 'Hello'}}
var obj2 = Object.create(obj1);
obj2.data.msg = "Hi!"; //overwrites, Why?
alert(obj1.data.msg); //=>'Hi!'

我认为 Object.create( )都使两个对象都指向同一原型,而赋值使两个对象都指向同一位置(而不仅仅是原型)。
但是在第3种情况下为什么要覆盖数据对象?

I think Object.create() just gives both makes both point to the same prototype, while assignment makes both object point to same location(not just prototype). But then why is the data object being overwritten in case 3?

推荐答案

var obj2 = Object.create(obj1)创建一个以obj1为原型的空(!)对象。

var obj2 = Object.create(obj1) creates an empty(!) object with obj1 as its prototype.

obj2.msg =嗨! 将(!)属性msg添加到obj2。

obj2.msg = "Hi!" adds(!) the property msg to obj2.

obj2.data.msg =嗨! 在obj2上查找属性数据,但obj2为空。因此,它将在obj2原型上寻找属性数据,而该对象恰好是obj1。然后将obj1.data上的味精更改为 Hi。

obj2.data.msg = "Hi!" looks for the property data on obj2, but obj2 is empty. So it looks for the property data on the prototype of obj2, which happens to be obj1. Then it changes msg on obj1.data to "Hi".

这篇关于使用Object.create()和使用赋值运算符有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆