在编写JavaScript类函数时,我经常使用this
。但是在使用它的同时,我想知道是否使用var
会有所不同。
var MyClass = function() {
this.x = 4;
return {
getVal: this.x
};
}
使用var
和不使用var
的区别:
var MyClass = function() {
var x = 4;
return {
getVal: x
};
}
这两者有什么区别,我应该在什么情况下使用哪个?
对于class
语法,同样适用这个问题:
class MyClass {
constructor(){
const x = 4;
}
}
对比
class MyClass {
constructor(){
this.x = 4;
}
}
this.x = 1; console.log(x);
不起作用,或者为什么const x = 1; console.log(this.x);
不起作用,或者为什么class A { constructor(){ const x = 1; } }; console.log((new A()).x);
不起作用等等。其中一部分是属性和变量之间的区别,另一部分是作用域,而这个问题则理想地将两者结合在一起。 - Sebastian Simonfunction A(){ this.x = 1; }; const a = A(); console.log(a.x, this.x, window.x, x);
在松散模式下由于缺少new
关键字而记录为1
1
1
1
;在严格模式下失败。this.x = 1; console.log(x);
在脚本中记录为1
,在模块中失败。 - Sebastian Simon