maq
maq

Reputation: 1226

Why use this in JavaScript OOP

well as of many i am also confuse with this in JS as i know how to use this in DOM but failed to understand in OOP as

a = "uff";
function Class1() {
  a = "";
}

function Class2() {
  this.a = "";
}
well = new Class1();
oh   = new Class2();
well.a = "bye";
oh.a = "ok";
console.log(well.a); // output: bye
console.log(oh.a);   // output: ok
console.log(a);      // output: ""

in above example using this or not is not effecting code so why do i use it and why last value of a is getting printing empty?? i will very thankful to all of you.

Upvotes: 0

Views: 90

Answers (2)

Andras
Andras

Reputation: 3055

in JavaScript, this referes to the object whose method is the one that's running, or the object that a constructor function is currently building. It doesn't have to be an object constructed with new.

var o = {
    f: function() { this.a = 2; }
}

o.a = 1;
o.f();
o.a;
// => 2

"a" is empty because the Class1 constructor function clears its value. An undeclared variable will be global, and the a in global scope is the one modified.

Upvotes: 0

Paul
Paul

Reputation: 36319

As the commenter mentioned, you're using all global variables, which ain't great for a lot of reasons (mostly around unintended consequences).

As to your question, what you are missing is that here:

function Class1(){
  a = "";
}

you just reset the global variable of a to "" from what it had been "uff".

Later, when you do:

well.a = "bye"

you're adding a new property to the well instance called a, which has nothing to do with the global variable a that you set.

Not for nothing, but none of what you're describing is actually JavaScript OOP. All you've worked with so far are object instances and their properties (as well as global variables).

Upvotes: 3

Related Questions