-2

I'm learning object concepts in JavaScript and have this doubt. Here is the link to the Bin http://jsbin.com/yoyepetewa/edit?js,console

function Obj() {
    //using 'this' and var produces the same result
    //this.x = 1;
    var x = 1;
}
var a = new Obj();
var b = new Obj();
a.x = 2;
b.x = 3;
console.log(`a's x = ${a.x}`);
console.log(`b's x = ${b.x}`);
karthikaruna
  • 3,042
  • 7
  • 26
  • 37
  • You can even omit `var x = 1;` and it will still work :P. But although it may be interesting that you have a doubt, what is your question? – trincot Mar 26 '17 at 16:54
  • No, they don't produce the same result. You would see that if you had code where those lines actually meant something. Remove for example the line `a.x = 2;` and see. – Sami Kuhmonen Mar 26 '17 at 16:55
  • @trincot The question is in the title. Yes, it needs to be in the question body as well. – Sebastian Simon Mar 26 '17 at 16:55
  • @Xufox, Ah, yes... Anyway, the duplicate you marked is indeed good reason to close. (NB: I knew a xufox on jijbent.nl -- you?) – trincot Mar 26 '17 at 16:57

1 Answers1

1

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875