Calling a method within a Javascript Object

2019-09-09 22:35发布

问题:

I'm trying to create a javascript object that can call other methods within itself. However, I'm running into a weird problem that I just can't seem to figure out.

I have the following code

myObjectDef = function() {
    this.init = function() {
        //do some stuff
        this.doSecondInit();
    }
    this.doSecondInit = function() {
        //do some more stuff
    }
}

myObject = new myObjectDef();
myObject.init();

I am getting an error that states "Message: Object doesn't support this property or method". And it ends at this.doSecondInit();. I can't quite figure out why it's doing this. My code runs great up to the call to the second method. How do I make this work?

回答1:

There's an extra set of parenthesis here:

this.doSecondInit() = function() {

You can't assign to the result of a function call, let alone to the result of a function that doesn't even exist.

After your edit, your thing seems to work fine:

http://jsfiddle.net/nabVN/

You sure you didn't have the same typo in your actual code? Better start getting used to not putting that () after every function call, which is probably a bad habit carried over from languages where functions aren't values.