Error with JavaScript Constructors Under Various Formats
I have an issue with code in the following format:
Test = {
baseConstructor: function( a, b ) {
this.a = a;
this.b = b;
},
object: new Test.baseConstructor( x, y )
};
I get an error saying that this.baseConstructor is not a con开发者_StackOverflow中文版structor. So what would I do in this case? I know I could reformat it without using the Test = {} style but is there a way to do it in this format.
You cannot use this
at this point as you are not inside an instance. Test.baseConstructor
also won't work since Test
has not been assigned yet when the code runs.
Here's a way to do it:
var Test = {
baseConstructor: function( a, b ) {
this.a = a;
this.b = b;
}
};
Test.object = new Test.baseConstructor(1, 2);
精彩评论