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

Defining custom objects and functions in JavaScript

本文关键字:对象 函数 自定义 定义 JavaScript      更新时间:2023-09-26

有人能解释一下这个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!?

您想要:

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

括号表示法采用字符串,但该字符串不会被解释为对象图表达式;这只是一根绳子。因此,window["Custom.prototype.msg"]创建了一个名为"Custom.protype.msg"的全局函数。

编辑—这也会起作用:

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

因此,如果你出于某种原因使用这些虚线列表表达式,如果你想把它们解释成这样,你就必须自己把它们分解。