gpt4 book ai didi

Javascript 继承 - "this"关键字丢失绑定(bind)?

转载 作者:行者123 更新时间:2023-11-29 17:19:55 26 4
gpt4 key购买 nike

我正在尝试在 Javascript 中学习更高级的继承方法,但无法弄清楚为什么我的继承对象在下面的 Eloquent Javascript 示例代码中失去了它的“this”关键字绑定(bind)。

我试过调用 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 绑定(bind)到灯笼?在我调用对象原型(prototype)中定义的方法的方法中,我缺少/不理解什么?谢谢。

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

最佳答案

console.log 不同,alert只需要一个参数。您需要连接字符串:

alert("you can not lift " + this.name + ".");

这样,lantern.take();Item.take.call(lantern); - 它们是等效的 - 将警告“你不能举起黄铜灯笼。”,而您的第三个示例取决于 this keyword 的值在当前执行中。顺便说一句,您的 take 函数不带参数。

关于Javascript 继承 - "this"关键字丢失绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13613135/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com