using 'this' and var produces the same result
No, it doesn't. var x = 1;
does absolutely nothing in terms of setting a property on the object.
But since you're adding an x
property later, you're not seeing that it doesn't do the same thing. If we look at x
before you set it to 2 or 3, we can see the difference.
Compare using this
:
function Obj() {
this.x = 1;
//var x = 1;
}
var a = new Obj();
console.log(`(1) a's x = ${a.x}`);
var b = new Obj();
console.log(`(1) b's x = ${b.x}`);
a.x = 2;
b.x = 3;
console.log(`(2) a's x = ${a.x}`);
console.log(`(2) b's x = ${b.x}`);
...to using var
:
function Obj() {
//this.x = 1;
var x = 1;
}
var a = new Obj();
console.log(`(1) a's x = ${a.x}`);
var b = new Obj();
console.log(`(1) b's x = ${b.x}`);
a.x = 2;
b.x = 3;
console.log(`(2) a's x = ${a.x}`);
console.log(`(2) b's x = ${b.x}`);
Notice how x
starts out undefined
.