2

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;
1

1 Answer 1

3

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"

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.