//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(old) 有什么区别?
最佳答案
引用 MDN's documentation on Object
,
The
Object
constructor creates an object wrapper for the given value. If the value isnull
orundefined
, it will create and return an empty object, otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value.
粗体文本是这里的关键。如果将对象传递给 Object
,它将按原样返回对象。这就是为什么,
console.log(np.hasOwnProperty('age'));
返回真
。你可以再做一次检查,像这样
var p = {
"name": "kannanrbk",
"age": 23
};
var np = new Object(p);
console.log(np === p);
# true
因为 np
和 p
是一回事。这里没有建立原型(prototype)链。
但是,当你使用Object.create
时,你传递给它的参数将被用作创建对象的原型(prototype),所以原型(prototype)链将在这种情况下建立。引用 Object.create
's MDN documentation ,
The
Object.create()
method creates a new object with the specified prototype object and properties.
关于javascript - object.create 和 new Object 的原型(prototype)区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28757350/