在JavaScript中定义自定义对象和函数(第2部分)

Defining custom objects and functions in JavaScript (Part 2)

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

根据我之前问的一个问题,我将如何限定这个字符串。。。

"MyCustomObject.prototype.foo.bar"

到此:

window['MyCustomObject']['prototype']['foo']['bar']

以对象形式?(它一定没有资格…

"window['MyCustomObject']['prototype']['foo']['bar']"

作为字符串!)。

作为参考,请考虑以下内容。。。(代码错误…需要修复(没有eval关键字))

var fn = "MyCustomObject.prototype.foo.bar";
var ptr = fn.split('.');
var ptrPath = 'window'
for(var index = 0; index < ptr.length; index++) {
    ptrPath += '[''' + ptr[index] + ''']';
}
ptrPath = function() {
    alert("Hello");
}

应该解决这个问题;

var inst = new MyObject();
inst.foo.bar();  //alerts...."Hello"

我修改了这个问题的答案以满足您的需要。

var getPropertyByName = function (fullString, context) {
        var namespaces = fullString.split(".");
        var functionName = namespaces.pop();
        for (var i = 0; i < namespaces.length; i++) {
            context = context[namespaces[i]];
        }
        return context[functionName];
};
getPropertyByName('MyCustomObject.foo.bar', window);

http://jsfiddle.net/jbabey/4GVUK/

您可以尝试以下方式:

var fn = "foo.prototype.bar";
var ptr = fn.split('.');
var func = ptr.reduce(function(a, b){
    return a[b] ? a[b] : a;
}, window);

工作演示

经过大量努力,我终于找到了解决方案。

Object.implement函数背后的思想是允许开发人员:

  1. 通过名称定义对象/函数(例如"Custom"或"Custom.protype.foo.bar"),而不管该对象是否存在。

  2. 定义对象/功能上下文(E.G窗口)

  3. 定义对象/功能实现

  4. 定义如果实现已经存在,是否覆盖对象/函数。

考虑Object.implement代码示例:

Object.implement = function(fn, context, implementation, override) {
    var properties = fn.split('.');
    var fnName = properties.pop();
    for(var index = 0; index < properties.length; index++) {
        if(!context[properties[index]]) {
            context[properties[index]] = { };
        }
        context = context[properties[index]];
    }
    if(!context[fnName] || override) {
        context[fnName] = implementation;
    }
};

我现在可以使用它来安全地创建/实现对象和函数。考虑一下这有点像一个"垫片"功能,如果一个功能不存在,就可以提供一个实现,但添加了现有功能后,现有功能也可能被覆盖:

Object.implement("HashTable", window, function() { }, true);
Object.implement("HashTable.prototype.bar", window, function() { alert("Hello World") }, true);
var ht = new HashTable();
ht.bar();

它适用于FireFox。。。我还没有在其他浏览器中进行测试!