Using javascript __proto__ in IE8

2019-04-11 21:26发布

Hi I have this two objects in javascript

var john = { firstname: 'John', lastname: 'Smith' }

var jane = { firstname: 'Jane' }

doing this:

jane.__proto__ = john;

I can access to jane's properties and also john's properties

If __proto__ is not supported in IE8 for example, what's the equivalent to write this:

jane.__proto__ = john;

Thanks!

2条回答
趁早两清
2楼-- · 2019-04-11 21:38

There is no equivalent or standard mechanism in IE. (The __proto__ property in Firefox is non-standard extension as is not specified in the ECMAScript standards.)

The [[prototype]] object can only be specified by setting the prototype property upon the function-object which acts as the constructor before the construction of a new object. The [[prototype]] can, however, be mutated later.

Anyway, here is a little example of specifying a [[prototype]] from an existing object. Note that the [[prototype]] assignment must be done before the new object is created. ECMAScript 5th edition introduces Object.create which can do the following and shallow-clone an object.

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
查看更多
We Are One
3楼-- · 2019-04-11 21:45

__proto__ currently is not an standard use.

Following the ECMAScript standard, the notation someObject.[[Prototype]] is used to designate the prototype of someObject. Since ECMAScript 5, the [[Prototype]] is accessed using the accessors Object.getPrototypeOf() and Object.setPrototypeOf().

So you could use getPrototypeOf() to access.

As in chrome,

> Object.getPrototypeOf(Object) === Object.__proto__
< true
查看更多
登录 后发表回答