我正在尝试在 Javascript 中学习更高级的继承方法,但无法弄清楚为什么我的继承对象在下面的 Eloquent Javascript 示例代码中失去了它的“this”关键字绑定。
例如,我尝试使用以下方法调用 take() 函数:
lantern.take(); // alerts you can not lift
Item.take.call(lantern, "the brass lantern"); // alerts you can not lift
lantern.take.call(this, "the brass lantern"); // alerts you can not lift
但是,这些都没有将 this.name 绑定到 lantern 吗?我在调用对象原型中定义的方法的方法中遗漏/不理解什么?谢谢你。
function forEachIn(object, action) {
for (var property in object) {
if (object.hasOwnProperty(property))
action(property, object[property]);
}
}
function clone(object) {
function OneShotConstructor(){}
OneShotConstructor.prototype = object;
return new OneShotConstructor();
}
Object.prototype.create = function() {
var object = clone(this);
if (typeof object.construct == "function")
object.construct.apply(object, arguments);
return object;
};
Object.prototype.extend = function(properties) {
var result = clone(this);
forEachIn(properties, function(name, value) {
result[name] = value;
});
return result;
};
var Item = {
construct: function(name) {
this.name = name;
},
inspect: function() {
alert("it is ", this.name, ".");
},
kick: function() {
alert("klunk!");
},
take: function() {
alert("you can not lift ", this.name, ".");
}
};
var lantern = Item.create("the brass lantern");
lantern.kick(); // alerts klunk