简体   繁体   English

在JavaScript中定义自定义对象和函数

[英]Defining custom objects and functions in JavaScript

Can someone explain what is wrong with this JavaScript example, and how to fix it if possible? 有人可以解释这个JavaScript示例出了什么问题,并在可能的情况下如何解决?

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

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". 因此, window["Custom.prototype.msg"]创建一个名为“ 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. 因此,如果出于某些原因要使用这些虚线列表表达式,则希望将它们解释为这样,则必须自行分解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM