0

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.

Paul
  • 32,974
  • 9
  • 79
  • 112
maq
  • 1,042
  • 1
  • 12
  • 32
  • 1
    All your variables are global, which is bad practice. `this` is rather unique in JavaScript, I'd suggest your read some articles on the internet first. There's a popular question here to get started http://stackoverflow.com/questions/3127429/javascript-this-keyword – elclanrs Dec 27 '14 at 22:38

2 Answers2

3

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).

Paul
  • 32,974
  • 9
  • 79
  • 112
0

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.

Andras
  • 2,827
  • 8
  • 16
  • Actually `this` refers to whatever you want it to refer to. `someOb.someMethod()` is just syntactic sugar for something like `(someOb.someMethod || someOb.prototype.someMethod).call(someOb);` Note the `someOb` as a parameter to `call`. Any object can be passed in there and `this` will refer to that object, not the object whose method is running. Even `new` is really just syntactic sugar for something close to `function() { var o = {}; someConstructorFunc.apply(o, arguments); return o; }` Constructors are not special, they're just normal JS functions. `new` is what makes them appear special. – gman Dec 27 '14 at 22:59