object.create 和 new Object 的原型区别 [英] Prototype difference between object.create and new Object

查看:69
本文介绍了object.create 和 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);

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

What is the difference between Object.create and new Object(old)?

推荐答案

引用 MDN 关于Object 的文档,

Quoting MDN's documentation on Object,

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

The Object constructor creates an object wrapper for the given value. 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. If the value is an object already, it will return the value.

粗体文本是这里的关键.如果您将一个对象传递给 Object,它将按原样返回该对象.这就是为什么,

The bold text is the key here. If you pass an object to Object, it will return the object as it is. That is why,

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

返回true.你可以再做一次检查,就像这样

return 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

因为 npp 是一回事.在这里,没有建立原型链.

because np and p are one and the same. Here, no prototype chain is established.

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

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. Quoting Object.create's MDN documentation,

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

The Object.create() method creates a new object with the specified prototype object and properties.

这篇关于object.create 和 new Object 的原型区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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