gpt4 book ai didi

javascript - 我什么时候应该使用 `this.x` 与 `var x` ?

转载 作者:数据小太阳 更新时间:2023-10-29 05:08:28 25 4
gpt4 key购买 nike

在创建 JavaScript 类函数时,我使用了 this。很多。但是在使用它时,我想知道使用 var 是否会有所不同。

var MyClass = function() {
this.x = 4;

return {
getVal: this.x
};
}

var 的使用对比:

var MyClass = function() {
var x = 4;

return {
getVal: x
};
}

有什么区别,什么时候应该使用哪个?

同样的问题适用于 class 语法:

class MyClass {
constructor(){
const x = 4;
}
}

对比

class MyClass {
constructor(){
this.x = 4;
}
}

最佳答案

带有 this 的标识符成为 public 属性,而带有 var 的标识符成为 private 变量。现在,应该使用 const 而不是 var;如果您不能对特定变量使用 const,请改用 let。访问语义相同。

当使用带有 this 关键字的标识符时,例如 this.x = 4;,您将使用键 "x"< 设置属性this 引用的对象上的值 4。由于 this 在类的上下文中引用了实例,因此此类属性成为类的实例成员,这意味着它们将在该类的每个新创建的实例。当你使用this时,意味着你打算在一个类中使用它,所以你需要使用new关键字实例化它,如下所示。

例子

function Foo() {
// Variables, scoped to the function. Private access.
const bar = 'I am bar';

// Properties, set on the instance. Public access
this.baz = 'I am baz';
this.secretBar = () => `It’s a secret to everybody: ${bar}.`;
}

const f = new Foo();

console.log(f.bar); // undefined
console.log(f.baz); // "I am baz"
console.log("bar" in f); // false; f does not have the property "bar".
console.log(f.secretBar()); // "It’s a secret to everybody: I am baz.";
// `secretBar` is in the scope of `Foo`, so it has access to its variables.

While making a JavaScript class function, I’m using this.A lot.But while using that, it’s making me wonder whether it would’ve made a difference to use var instead.

有显着差异。除非另有需要,否则不应使用不想出现在类实例中的 this 关键字创建变量。

关于javascript - 我什么时候应该使用 `this.x` 与 `var x` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11162005/

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