最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - When should I use `this.x` vs. `var x`? - Stack Overflow

programmeradmin3浏览0评论

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.

var MyClass = function() {
  this.x = 4;
  
  return {
    getVal: this.x
  };
}

versus the same thing with the use of var:

var MyClass = function() {
  var x = 4;
  
  return {
    getVal: x
  };
}

What’s the difference and when should I use which?

The same question applies to the class syntax:

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

versus

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

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.

var MyClass = function() {
  this.x = 4;
  
  return {
    getVal: this.x
  };
}

versus the same thing with the use of var:

var MyClass = function() {
  var x = 4;
  
  return {
    getVal: x
  };
}

What’s the difference and when should I use which?

The same question applies to the class syntax:

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

versus

class MyClass {
  constructor(){
    this.x = 4;
  }
}
Share Improve this question edited Dec 15, 2022 at 2:43 Sebastian Simon 19.5k8 gold badges60 silver badges84 bronze badges asked Jun 22, 2012 at 18:22 KristianKristian 21.8k19 gold badges107 silver badges183 bronze badges 2
  • I’ve edited this question and the top answer — maybe a bit too heavily. This question needed an update to be more useful to new devs today. Novices are getting confused by this and are asking why this.x = 1; console.log(x); does not work, or why const x = 1; console.log(this.x); does not work, or why class A { constructor(){ const x = 1; } }; console.log((new A()).x); does not work, etc. One part is the difference between a property and a variable, another part is scope, and this question, ideally, nicely bines the two. – Sebastian Simon Commented Dec 15, 2022 at 2:49
  • There’s still a lot of context missing, notably how the "this" keyword works, the difference between strict and sloppy mode, between scripts and modules, implicit globals, etc. Two examples: function A(){ this.x = 1; }; const a = A(); console.log(a.x, this.x, window.x, x); logs 1 1 1 1 because of the missing new keyword in sloppy mode; fails in strict mode. this.x = 1; console.log(x); logs 1 in scripts, fails in modules. – Sebastian Simon Commented Dec 15, 2022 at 2:58
Add a ment  | 

4 Answers 4

Reset to default 9

Identifiers with this bee public properties, whereas those with var bee private variables. Nowadays, const should be used instead of var; if you can’t use const for a specific variable, use let instead. The access semantics are the same.

When using an identifier with the this keyword, like this.x = 4;, you’re setting a property with the key "x" and the value 4 on the object referenced by this. Since this refers to the instance in the context of a class, such properties bee instance members of the class, which means they will be available in each newly created instance of that class. When you use this, it means that your intention is to use it in a class, so you need to instantiate it using the new keyword as shown below.

Example

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.

There is a significant difference. You should not create variables with the this keyword that you don’t want to appear in instances of your class, unless otherwise needed.

You can access this.x with myClass.x, but you can't do that for var x case. This is all about encapsulation.

If you are not going to need to do inheritance, closures (the var case) and objects (the this case) basically do the same thing and are roughly interchangeable.

Differences to keep in mind:

  • When you use "this" the constructor needs to be called with "new" and methods need to be called with .call if you store them on a variable or pass them as a callback.

  • There might be performance differences if you instantiate lots of objects (current engines may with objects better - but only if you put the methods in the prototype instead of setting them in the constructor)

  • Variables declared with "var" are private and cannot be accessed outside the function. Sometimes this is OK but this can stop you from doing inheritance (there is no notion of "protected in Javascript")

Expressions like this.x refer to properties; they are like instance variables. These variables have public scope. They work as class variables in object oriented programming.

On the other hand, var x; has limited scope. These are variables that behave like private instance variables and are accessible within the local scope.

发布评论

评论列表(0)

  1. 暂无评论