我一定有一个你忘记一切的日子:)
虽然@NilColor 的答案是正确的,但我确实知道我只是没有戴上正确的帽子。
无论如何,我决定我仍然喜欢有一个包装器的想法,当你将它附加到你的对象时,它需要更少的特异性。并且不那么冗长。
所以我是按照我原来的思路写的,你可能会喜欢。
myObj.wrap = function(path, context){
var wrapper,
method = ( typeof path != 'string' && context )? path : this,
context = (typeof path === 'object' && context === undefined)?
path : (context || this);
if (typeof path === 'string'){
path = path.split('.');
for ( var i = 0; i < path.length; i++ ){
method = method[path[i]];
if ( context === true )
context = ( i === path.length - 2 )? method : context;
};
};
wrapper = function(){
method.apply(context, arguments);
};
return wrapper;
}
用法:
将任意数量的嵌套方法绑定到 myObj
myObj.wrap('foo') //binds myObj.foo to myObj
// or
myObj.wrap('foo.bar') //binds myObj.foo.bar to myObj
//or if myObj is a function
myFunc.wrap() // binds myFunc to myFunc
将 myObj 的方法绑定到另一个对象
myObj.wrap('foo.bar', someObj) //binds myObj.foo.bar to someObj
//or if myObj is a function
myFunc.wrap(someObj) //Binds myFunc to someObj
将嵌套方法绑定到它的父级
myObj.wrap('foo.bar', true) // binds myObj.foo.bar to myObj.foo
用作助手
myObj.wrap(someFunc, someObj) //binds someFunc to someObj
如果您不是在方法绑定的上下文中寻找原始问题的答案。
myObj.getProps = function(path, context){
var context = context || this;
path = path.split('.');
for ( var i = 0; i < path.length; i++ ){
context = context[path[i]];
};
return context;
};
用法:
附加到对象或作为独立功能
获取属性
myObj.getProps('foo.bar') // returns mayObj.foo.bar
给它一个上下文对象
myObj.getProps('user.name', myAccounts) // returns myAccounts.user.name
将其用作独立功能替换
myObj.getProps = function(path,context){....}
和
function getProps(path,context){....}
笔记
如果将其用作独立函数,您需要记住它将从this
. 因此,如果它是在全局范围内定义的,则需要提供完整路径。
例如
getProps('myObj.foo.bar')
您仍然可以使用上下文选择器来更改引用对象。