这个例子的灵感来自Alex Sexton的博客文章Understanding JavaScript Inheritance
var defaults = {};
defaults.x = 1;
var myObject = Object.create(defaults);
console.log(myObject); // {x:1}
myObject.x = 2;
console.log(myObject); // {x:2, x:1}
console.log(myObject.x); // 2问:有没有办法把值1从myObject中取回来?我在想像这样的东西:
console.log(myObject.parent.x);发布于 2013-04-20 03:05:46
所有主要浏览器的最新版本都支持Object.getPrototypeOf(),但需要一些额外的代码才能与IE8及更早版本(check this)兼容。如果这对你来说不是问题,你可以这样做:
Object.getPrototypeOf(myObject).x检查jsfiddle。
发布于 2013-04-20 01:12:23
这将适用于Chrome和Firefox。
>>> myObject.__proto__.x
1发布于 2013-04-20 01:31:23
您可以引用myObject中的默认值
myObject.parent = defaults;
console.log(myObject.parent.x);// 1https://stackoverflow.com/questions/16109983
复制相似问题