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!?

1 Answer 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.

Sign up to request clarification or add additional context in comments.

8 Comments

That's exactly what I don't want, sorry see my revised example.
@activwerx well want or don't want whatever, your code won't work as written because it's simply not what JavaScript does. I'll add another suggestion to the answer.
Thanks, sorry for the confusion!
As a curiosity, is there any reason in particular why you wouldn't want to use that notation?
And thanks for the update, I will accept your answer on that basis!
|

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.