开发者

How to get to my ancestor’s overridden method using Crockfords's Object.create() (Javascript)

开发者 https://www.devze.com 2022-12-10 19:02 出处:网络
if (typeof Object.create !== \'function\') { Object.create = function (o) { function F() {} F.prototype = o;
if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}
var o1 = {};
o1.init = function(){
   alert('o1');
};
var o2 = Object.create(o1);
o2.init = function(){
   // how would I call my ancessors i开发者_C百科nit()?
   alert('o2');
};
o2.init();


JavaScript functions are objects and have two useful methods to invoke the function:

Function.call(scope, [arg1, ...])
Function.apply(scope, args)

You can use one of these to call the parent implementation, explicitely passing this as the scope parameter, so that in the parent implementation, this refers to the child object:

var o1 = {
    name : "One",
    init : function() {
        alert("o1: " + this.name);
    }
};

var o2 = Object.create(o1);
o2.name = "Two";
o2.init = function() {
    o1.init.call(this);
    alert("o2: " + this name);
};

This will alert: o1: Two and o2: Two.


Maybe this is oversimplifying what you’re trying to accomplish ... would placing o1.init() in the o2 init function work?

o2.init = function(){
   // how would I call my ancessors init()?
   alert('o2');
   o1.init();
};

Out of curiosity, was "ancessors" a spelling error for "ancestor’s" or does "ancessors" mean something specific here? Did you mean o2’s "parent" object?


In browsers that support it, you could use the Object.getPrototypeOf function, like this:

o2.init = function(){
    Object.getPrototypeOf(this).init.call(this);
    alert('o2');
};

This would get the prototype of o2 (o1) and apply its init method to this (o2), just like a super.init() in other languages.

UPDATE:

The Object.getPrototypeOf function could be implemented like this:

if ( typeof Object.getPrototypeOf !== "function" ) 
{
    if ( typeof ({}).__proto__ === "object" ) 
    {
        Object.getPrototypeOf = function(object)
        {
            return object.__proto__;
        };
    } 
    else 
    {
        Object.getPrototypeOf = function(object)
        {
            // May break if the constructor has been tampered with
            return object.constructor.prototype;
        };
    }
}

Found on this link: http://ejohn.org/blog/objectgetprototypeof/

0

精彩评论

暂无评论...
验证码 换一张
取 消