菜鸟问题,已搜索但未找到该特定问题的答案。 我正在构造一个对象,并使用“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/