gpt4 book ai didi

javascript - 将代码转换为对象时如何使用 'this'?

转载 作者:行者123 更新时间:2023-11-28 01:07:01 24 4
gpt4 key购买 nike

因此我可以在网页上的多个位置重用代码,我将其转换为面向对象的 Javascript。原始代码如下所示:

foo = 42;
function bar(a,b) {
foo = a * foo + b;
}
...
bar(1,1)

我想我希望它看起来像这样:

function Example() {
this.foo = 42;
this.bar = function() {
this.foo = a * this.foo + b;
}
}
var one = new Example();
var two = new Example();
...
one.bar(1,1);
two.bar(2,3);

但是,我不确定我是否在嵌套函数中正确使用了“this”。我注意到我要转换的一些函数是已经在其主体中引用“this”的事件处理程序。如何区分事件处理程序中已有的“this”和我想用来访问局部变量的“this”?

最佳答案

在示例类/函数中创建本地 var,然后您可以引用适当的 this 对象。

function Example() {
var self = this;
this.foo = 42;
this.bar = function() {
self.foo = a * self.foo + b;
}
}

关于javascript - 将代码转换为对象时如何使用 'this'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24948252/

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