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

标签 javascript oop

因此我可以在网页上的多个位置重用代码,我将其转换为面向对象的 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/

相关文章:

javascript - Accordion 项目重复

javascript - Node.js 和 Express : How to return response after asynchronous operation

javascript - Angular 2 中的异步等待

PHP 字符串到 javascript 可能会破坏代码 - 我猜是某个字符有问题吗?

java - 使用单一数据结构的双向映射

java - 在 Arrays.reduce(...) 中调用对象方法

javascript - Google 已禁用此应用程序的 map API

python - 在python中模拟私有(private)变量

java - OOPS ( JAVA ) 中的类设计

像 Obj-C 这样的 Java 类别?