javascript - object.create 和 new Object 的原型(prototype)区别

标签 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(old) 有什么区别?

最佳答案

引用 MDN's documentation on Object ,

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,它将按原样返回对象。这就是为什么,

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

返回。你可以再做一次检查,像这样

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

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

因为 npp 是一回事。这里没有建立原型(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/

相关文章:

javascript - 函数构造函数 - 使用原型(prototype)添加函数给出 - 未捕获的语法错误 : Unexpected token {

javascript - JavaScript 中的原型(prototype)

javascript - 从 JSON 解析数组,其中每个字段键都是一个数字

javascript - PushState 在 IE 7 中导致回发>

JavaScript - 点击图片

javascript - 使数组对象都具有相同的键

javascript - 在 JavaScript 中使用原型(prototype)在现实世界中有什么优势吗?

javascript - 通过 JavaScript 验证 PHP 验证码

javascript - 在每个 "x"元素后打开和关闭一个 div

python - 如何迭代创建通用树的类属性?