2012-08-30 59 views
1

基于一个问题,在此之前,我问,我怎么有资格这串...定义自定义对象和函数在JavaScript(第2部分)

"MyCustomObject.prototype.foo.bar" 

这样:

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

在对象形式? (它不一定符合...

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

... as a string!)。

作为参考,请考虑以下...(代码是错误的...它需要固定(不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" 

回答

0

最后经过很大的努力,我已经找到了解决方案。

的Object.implement功能背后的想法是,以允许开发者:

  1. 通过名称定义的对象/功能(例如,“自定义”或“Custom.prototype.foo.bar”),不管那个物体是否存在。

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

  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中...我还没有在其他浏览器中测试!

0

我修改了答案this question以满足您的需求。

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/

+0

您的解决方案是否需要'MyCustomObject.foo.bar'才能实现,然后才能返回非undefined的内容? - 基本上我想要一个函数来限定字符串(在本例中)属性,然后可以赋值(或实现)属性,但有时可能该属性不存在于第一位,因此函数赋值将是该属性第一次被定义......我希望这是有道理的!? – series0ne

+0

@activwerx不,它只会在它已经被定义时才起作用 – jbabey

+0

:-(有什么办法可以做到吗?例如,我可以做window ['CustomObject'] = function(){};然后我将拥有一个名为CustomObject的可构造对象,但我希望能够对嵌套属性做同样的工作。 – series0ne

0

你可以试试这个方法:

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

The working demo.

+0

我终于搞清楚了我想要做的事情,请考虑我的答案,并酌情给予反馈或批评。 – series0ne