I thought scope chain would make the first “test = new test();” work, but it doesn’t. why?
var tool = new Tool();
tool.init();
function Tool(){
var test;
function init(){
//does not work, undefined
test = new Test();
//does work
this.test=new Test();
console.log(test);
}
}
function Test(){
}
EDIT: by not working i mean, it says that test is ‘undefined’
It’s simple. Your
Toolinstance does not have ainitmethod. Theinitfunction in your code is merely a local function of theToolconstructor.Toolinstances do not inherit such functions.If you want your
Toolinstances to have ainitmethod, you can:assign it as a method inside the constructor:
or assign it to
Tool.prototype(outside of the constructor!):The second option performs better, since all instances share the same
initfunction. (In the first option, each instance gets its owninitfunction which is created during the constructor call.)