5
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 init()?
   alert('o2');
};
o2.init();
4

3 回答 3

3

JavaScript 函数是对象,有两个有用的方法来调用函数:

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

您可以使用其中之一来调用父实现,显式地this作为scope参数传递,以便在父实现中this引用子对象:

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);
};

这将警告:o1: Twoo2: Two

于 2009-11-01T13:39:22.837 回答
2

也许这过于简化了您要完成的工作……将 o1.init() 放在 o2 init 函数中是否可行?

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

出于好奇,“祖先”是“祖先”的拼写错误,还是“祖先”在这里有特定的含义?您是说 o2 的“父”对象吗?

于 2009-11-13T09:11:44.707 回答
0

在支持它的浏览器中,您可以使用该Object.getPrototypeOf功能,如下所示:

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

这将获得o2( o1) 的原型并将其init方法应用于此 ( o2),就像super.init()其他语言中的 a 一样。

更新:

Object.getPrototypeOf功能可以这样实现:

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;
        };
    }
}

在此链接上找到: http: //ejohn.org/blog/objectgetprototypeof/

于 2012-10-19T14:26:14.680 回答