object.create和new Object之间的原型区别

时间:2015-02-27 04:07:33

标签: javascript object prototype

//The last link of the prototype chain always be Object.prototype. 
var o = {"name":"kannanrbk", "age": 21};
//extending object.
var no = Object.create(o); //Now the new object is linked to the old object o. 
no.name = "Bharathi Kannan R";
console.log(o.name); //Still be 'kannanrbk'. Because, this prototype chain will be used only for retrieval.
//In js prototype is dynamic. If we add new property in this prototype. It will be visible immediately. 
o.sex = "Male";
console.log(no.sex);

//To find the property of the type 
console.log(typeof no.sex);

/**
* Enumeration
*/
for(var k in no) {
    console.log(no[k]);
}

//To check whether the property is belongs to the object.
console.log(no.hasOwnProperty('sex')); //false, it won't check the prototype chain.

var p = {"name":"kannanrbk","age":23};
var np = new Object(p);

//Why it returns true?
console.log(np.hasOwnProperty('age')); //true. 
np.age = 25;

//How the value is updated in entire prototype chain?
console.log(p.age);

Object.create和new Object(旧)有什么区别?

1 个答案:

答案 0 :(得分:3)

引用MDN's documentation on Object

  

Object构造函数为给定值创建一个对象包装器。如果值为nullundefined,则它将创建并返回一个空对象,否则,它将返回与给定值对应的Type对象。 如果该值已经是某个对象,则会返回该值。

粗体文字是这里的关键。如果将对象传递给Object,它将按原样返回对象。这就是原因,

console.log(np.hasOwnProperty('age'));

返回true。你可以再做一次检查,比如这个

var p = {
    "name": "kannanrbk",
    "age": 23
};
var np = new Object(p);

console.log(np === p);
# true

因为npp是同一个。在这里,没有建立原型链。

但是,当你使用Object.create时,传递给它的参数将被用作创建的对象的原型,因此在这种情况下将建立原型链。引用Object.create's MDN documentation

  

Object.create()方法使用指定的原型对象和属性创建一个新对象。