Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use this.x vs var x?

Tags:

javascript

oop

While making a javascript class function, i'm using this. a lot. But while using that, its 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
    };
}

Whats the difference and when should i use them?

like image 338
Kristian Avatar asked Jun 22 '12 18:06

Kristian


People also ask

What is the difference between X 10 and X == 10?

Answer: a=10 is used to assignment, means the value of a will be 10. a==10 is a binary operator, and used to do comparison .

What is the difference between the VAR X 1 and X 1?

js? The former creates a local variable, while the latter creates a global variable. If you use strict mode, only var x = 1 would work. If you are using 'use strict' in your js file then later one will give error.

Why this is used in JavaScript?

In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.

What is the difference between VAR x 0 and let x 0?

The main difference is scoping rules. Variables declared by var keyword are scoped to the immediate function body (hence the function scope) while let variables are scoped to the immediate enclosing block denoted by { } (hence the block scope).


1 Answers

Variables with this become public variables while those with var become private variables.

The variables or function declared with this keyword become instance members of the class which means they will be available in each newly created instance of that class. When you use this, you have created a class and you need to instantiate it using new keyword as shown below.

Example:

function Foo() {
  // private var
  var bar = 'I am bar';
  // public var
  this.baz = 'I am baz';
}

var f = new Foo;
console.log(f.bar); // undefined
console.log(f.baz); // I am baz

While making a javascript class function, i'm using this. a lot. But while using that, its making me wonder whether it would've made a difference to use var instead.

There is significant difference, you should not creates variables with this keyword that you don't want to appear in instances of your class unless otherwise needed. That simply creates an overhead and is computational waste as Crockford calls it.

like image 180
Blaster Avatar answered Nov 15 '22 00:11

Blaster