ClementParis016
ClementParis016

Reputation: 519

JavaScript assign function to object property

I was looking at the source code of a JavaScript library and encountered something like this in a class definition:

var MyClass = function() {
    function doSomething() {
        // function definition
    }

    this.doSomething = function() {
        doSomething();
    };
}

So, my question is: is there any reason someone would do this instead of simply assigning the function to the object method like this:

this.doSomething = doSomething;

Upvotes: 2

Views: 3619

Answers (1)

James Thorpe
James Thorpe

Reputation: 32222

It depends on exactly what doSomething is actually doing. There is a difference in how this will be bound within the function. If you call it as per your example, it won't have this bound to the object, whereas if you call it with it assigned directly to a property, then this will be bound to the instance:

var MyClass = function() {
  this.n = "Bob";
  function doSomething() {
    console.log(this.n);
  }

  this.doSomething = function() {
    doSomething();
  };
  this.doSomethingDirect = doSomething;
}

var x = new MyClass();

x.doSomething();        //undefined
x.doSomethingDirect();  //"Bob"

Upvotes: 3

Related Questions