javascript - 对象方法中的冗余 Javascript this?

标签 javascript this

菜鸟问题,已搜索但未找到该特定问题的答案。 我正在构造一个对象,并使用“this”关键字引用参数的参数:

function Obj(a, b, c) {
  this.a = a;
  this.b = b;
  this.c = c;
  this.addMe = function() {
    alert(this.a + this.b + this.c);
  };
}

我的问题很简单:如果 a、b 和 c 仅存在于对象中(换句话说,没有使用相同名称声明的全局变量),在内部使用它们时是否需要“this”关键字addMe() 方法?该方法不能简单地写成:

this.addMe = function() {
  alert(a + b + c);
};

当我通过创建一个新的 Obj 实例来运行这段代码时,它的工作方式完全相同。并且(不是我会这样做)如果我为 a、b 和 c 创建的全局变量的值与我在实例化新 Obj 时使用的参数不同,则这些变量与方法调用的结果无关。那么,如果我不在方法中使用“this”,我是否遗漏了一些会回来咬我的东西?

最佳答案

演示使用a + b + c的区别/问题

function Obj(a, b, c) {
  this.a = a;
  this.b = b;
  this.c = c;
  this.addMe = function() {
    console.log('addMe', this.a + this.b + this.c);
  };
  this.brokenAddMe = function() {
    console.log('brokenAddMe', a + b + c);
  };
}
var o = new Obj(1,2,3);
o.addMe(); // should be and is 6
o.brokenAddMe(); // should be and is 6
o.a = 4;
o.addMe(); // should be and is 9
o.brokenAddMe(); // should be 9 but still is 6

关于javascript - 对象方法中的冗余 Javascript this?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45557270/

相关文章:

php - 我在将 PHP 中的数组转为 JSON 结构用于 Javascript 时遇到问题

javascript - Meteor:OSM的Oauth1.0a登录服务

javascript - 使用 jquery 将 html 图像添加到 div/table

java - 在构造函数中使用 'this' 而不抛出 NullPointerException

javascript - JQuery:在 .each() 循环中使用 "this"

javascript - 将变量传递给在循环中调用的异步 JavaScript 函数 (React)

c++ - 速度差 : separate functor VS operator() inside a big class with *this

javascript - 从一行字符串中提取价格的最佳方法是什么?

javascript - 为什么我的 html-node 保留类 ng-hide 属性 ng-show=true?

jquery - 在 Jquery Ajax 响应中使用选择器和 $(this)