你好,我在 javascript 中有这两个对象
var john = { firstname: 'John', lastname: 'Smith' }
var jane = { firstname: 'Jane' }
这样做:
jane.__proto__ = john;
我可以访问 jane 的属性,也可以访问 john 的属性
例如,如果 IE8 不支持 __proto__
,那么这样写的等价物是什么:
jane.__proto__ = john;
谢谢!
最佳答案
IE 中没有等效或标准的机制。 (Firefox 中的 __proto__
属性是非标准扩展,因为在 ECMAScript 标准中未指定。)
[[prototype]] 对象只能通过在函数对象上设置prototype
属性来指定,该函数对象之前 构建一个新对象。然而,[[prototype]] 以后可以改变。
无论如何,这是一个从现有对象指定 [[prototype]] 的小例子。请注意,[[prototype]] 赋值必须在创建新对象之前完成。 ECMAScript 第 5 版介绍 Object.create它可以执行以下和浅克隆一个对象。
function create (proto) {
function f () {}
f.prototype = proto
return new f
}
var joe = create({})
var jane = create(joe)
joe.name = "joe" // modifies object used as jane's [[prototype]]
jane.constructor.prototype === joe // true
jane.__proto__ === joe // true -- in Firefox, but not IE
jane.name // "joe" -- through [[prototype]]
jane.constructor.prototype = {} // does NOT re-assign jane's [[prototype]]
jane.name // "joe" -- see above
关于javascript - 在 IE8 中使用 javascript __proto__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12431911/