0

I am trying to init a method in my case. I have something like

var test = new testObj()

 function testObj(){
        this.init();
    }

 testObj.prototype.init = function(){        
    //do something
 }

However, I am getting testObj has no method of init error from the console.

I am not sure what happen. Can someone help me out on this? Thanks a lot!

1
  • Common people why the downvote rush.... it is a perfectly valid question with a real problem Commented Jan 25, 2014 at 0:41

1 Answer 1

3

it is because the order of your script

function testObj() {
    console.log(this)
    this.init();
}

testObj.prototype.init = function () {
    //do something
}

var test = new testObj();

The function declaration will get hoisted to the top of the declaring scope, so you are able to create a new testObj instance but the enhancement of the prototype has not happened when the constructor is called so you won't get init method.

After hoisting the code could look like below, when new testObj() is executed, it calls the constructor function but the init method is not yet added to the prototype of testObj

function testObj() {
    console.log(this)
    this.init();
}

var test = new testObj();

testObj.prototype.init = function () {
    //do something
}
Sign up to request clarification or add additional context in comments.

1 Comment

oh boy..my brain is dead. I can't even find out this. thanks for the help

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.