0

Can someone explain what is wrong with this JavaScript example, and how to fix it if possible?

    // I can define objects / functions like this.
    window['Custom'] = function() { };
    //Works...I now have a 'Custom' function in scope... I can now do this...

    var c = new Custom(); // WORKS!!

    //This does not seem to work!
    window['Custom.prototype.msg'] = function(msg) {
        alert(msg);
    };

    // I DO NOT WANT TO DO THIS!
    Custom.prototype.msg = function(msg) { alert(msg); };


    x.msg("Hello");
    //FireFox Error: TypeError: x.msg is not a function...
    // HOW DO I FIX THIS!?
4

1 回答 1

1

You want:

window.Custom.prototype.msg = function(msg) { ... }

The bracket notation takes a string, but the string won't be interpreted as an object graph expression; it's just a string. Thus, window["Custom.prototype.msg"] creates a global function called "Custom.prototype.msg".

edit — this would also work:

window["Custom"]["prototype"]["msg"] = function(msg) { ... }

So if you're working with those dotted list expressions for some reason, if you want them to be interpreted as such you'll have to break them up yourself.

于 2012-08-30T13:37:26.560 回答