0
MyClass = function() {
    var init = function() {
        console.log("Initializing");
    }
    this.init();
}
var myInstance = new MyClass();

When I run the above I get

TypeError: Object [object Object] has no method 'init'

2 Answers 2

4

Local variables in the constructor's scope don't become properties of the instance.

Instead of var init = function...;, use this.init = function...;

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

Comments

3

It's because by declaring init as a var, or a local variable rather than a property of the object. As such, init does not become a member function of your object, which is why your code failed to run as you expected. Initialize it as this.init = function() { instead to achieve the expected behaviour.

http://jsfiddle.net/Y2Rvq/

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.