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?
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 .
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With