我们考虑一下这段代码:
(function(){
var a = {"id": "1", "name": "mike", "lastname": "ross"};
var b = JSON.parse('{"id": "1", "name": "mike", "lastname": "ross"}');
var c = Object.create({"id": "1", "name": "mike", "lastname": "ross"});
document.write(typeof(a) + "</br>");
document.write(typeof(b) + "</br>");
document.write(typeof(c) + "</br>");
})();?
Run Code Online (Sandbox Code Playgroud)
问题
请添加对您的答案的引用.
演示.
a并b导致"indentical"对象(与{a:1}abd 相同的方式{a:1}相同).
JSON.parse解析输入的JSON 字符串,并输出解析的值.在这种情况下,一个对象.
c是不同的.Object.create创建一个新对象,并将原型设置为第一个参数.您可以验证它c.__proto__.id是否等于1(前两种情况下不可用).
乍一看,所有这三种方法都会产生"相同"的对象:在所有情况下id都会读取属性1.在第三种情况下,此结果是由原型继承引起的.这提供了一个可能的功能:
var x = Object.create({id:1});
x.id = NaN;
console.log(x.id);
// NaN
delete x.id;
console.log(x.id);
// 1 - The old value is back :)
// ( for x = {id: 1};, the old value would be gone! )
Run Code Online (Sandbox Code Playgroud)
a并且b实际上是相同的(它们具有相同的属性,具有相同的值,在相同的位置).c完全不同.如果将对象记录到控制台而不是将有限的信息打印到页面,则可以看到明显的区别:

c是右边的那个.它创建了一个没有自己属性的对象.您指定的属性实际上prototype是c.原因是第一个参数Object.create是prototype要创建的对象.
请注意,您可以使用Object.create获得相同的效果 - 只需Object.prototype作为第一个参数传递:
var d = Object.create(Object.prototype, {
"id": { "value": 1 }, //values are 'property descriptors'
"name": { "value": "mike" }
//etc...
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
366 次 |
| 最近记录: |