简体   繁体   English

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

[英]Prototype difference between object.create and new Object

//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);

What is the difference between Object.create and new Object(old)? Object.create和new Object(旧)有什么区别?

Quoting MDN's documentation on Object , 引用MDN关于Object的文档

The Object constructor creates an object wrapper for the given value. Object构造函数为给定值创建一个对象包装器。 If the value is null or undefined , it will create and return an empty object, otherwise, it will return an object of a Type that corresponds to the given value. 如果值为nullundefined ,则它将创建并返回一个空对象,否则,它将返回与给定值对应的Type对象。 If the value is an object already, it will return the value. 如果值已经是一个对象,它将返回该值。

The bold text is the key here. 粗体文字是这里的关键。 If you pass an object to Object , it will return the object as it is. 如果将对象传递给Object ,它将按原样返回对象。 That is why, 这就是为什么,

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

return true . 返回true You can do one more check, like this 你可以再做一次检查,就像这样

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

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

because np and p are one and the same. 因为npp是同一个。 Here, no prototype chain is established. 在这里,没有建立原型链。

But, when you use Object.create , the parameter you pass to that will be used as the prototype of the object created, so the prototype chain will be established in that case. 但是,当您使用Object.create ,您传递给它的参数将用作创建的对象的原型,因此在这种情况下将建立原型链。 Quoting Object.create 's MDN documentation , 引用Object.create的MDN文档

The Object.create() method creates a new object with the specified prototype object and properties. Object.create()方法使用指定的原型对象和属性创建一个新对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM