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();
最佳答案
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: Two
和 o2: Two
。
关于javascript - 如何使用 Crockfords 的 Object.create() (Javascript) 获取我祖先的重写方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1657137/