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

标签 javascript oop

在创建 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/

相关文章:

javascript - 我需要一些帮助来理解这种方法的组合(reduce、concat 和 map)

c++ - 使用模板化函数减少代码

perl - Perl 中的多级继承

javascript - 单击以加载远程数据的挂起 Bootstrap 模式

javascript - 延迟回调直到脚本被添加到文档?

javascript - node-postgres:一次更新多条记录

javascript - 在哪里放置 jQuery 脚本?

c++ - 成员初始值设定项列表的使用如何防止在 C++ 中创建冗余对象?

javascript - 对象 JavaScript

javascript - Javascript OOP 中的未知未定义