Identifiers with this
become public properties, whereas those with var
become 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 become 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.