Skip to main content
added a way to avoid using 'this' with a constructor function
Source Link
Gabe Moothart
  • 32.3k
  • 15
  • 81
  • 100

The identity of this is a common problem in javascript. It would also break if you tried to create a shortcut to doSomething:

var do = Bob.doSomething;
do(); // this is no longer pointing to Bob!

It's good practice to not rely on the identity of this. You can do that in a variety of ways, but the easiest is to explicitly reference Bob instead of this inside of doSomething. Another is to use a constructor function (but then you lose the cool object-literal syntax):

var createBob = function() {
    var that = {};
    
    that.Stuff = '';
    that.init = function() {
        that.Stuff = arguments[0];
    };

   that.doSomething = function() {
       console.log( that.Stuff );
   };

   return that;   
}

var bob = createBob();

The identity of this is a common problem in javascript. It would also break if you tried to create a shortcut to doSomething:

var do = Bob.doSomething;
do(); // this is no longer pointing to Bob!

It's good practice to not rely on the identity of this. You can do that in a variety of ways, but the easiest is to explicitly reference Bob instead of this inside of doSomething.

The identity of this is a common problem in javascript. It would also break if you tried to create a shortcut to doSomething:

var do = Bob.doSomething;
do(); // this is no longer pointing to Bob!

It's good practice to not rely on the identity of this. You can do that in a variety of ways, but the easiest is to explicitly reference Bob instead of this inside of doSomething. Another is to use a constructor function (but then you lose the cool object-literal syntax):

var createBob = function() {
    var that = {};
    
    that.Stuff = '';
    that.init = function() {
        that.Stuff = arguments[0];
    };

   that.doSomething = function() {
       console.log( that.Stuff );
   };

   return that;   
}

var bob = createBob();
Source Link
Gabe Moothart
  • 32.3k
  • 15
  • 81
  • 100

The identity of this is a common problem in javascript. It would also break if you tried to create a shortcut to doSomething:

var do = Bob.doSomething;
do(); // this is no longer pointing to Bob!

It's good practice to not rely on the identity of this. You can do that in a variety of ways, but the easiest is to explicitly reference Bob instead of this inside of doSomething.