我有一个看起来像这样的对象:
var foo = {
parent: {
childOne: {
prop: 1,
doSomething: function(){
return this.prop;
}
},
childTwo: {
prop: 2,
doSomething: function(){
return this.prop;
}
}
},
other: {
action: function(){
return foo.parent.childOne.doSomething() +
foo.parent.childTwo.doSomething();
}
}
}
window.alert(foo.other.action());
这里的 doSomething()
函数绝对是重复的代码,我想避免它,这与继承解决的问题类似。
我在想是否有任何方法可以做以下事情:
parent: {
doSomething: function(){
return this.prop;
}
}
但不确定如何实际实现它,这可能吗?
最佳答案
您仍然需要上下文绑定(bind):
function something(context){
return function(){
return context.prop;
}
}
现在:
doSomething: something(this);
现在,只需像在 foo.other.action
方法中那样调用 doSomething()
即可。
关于javascript - 如何共享作为对象属性的函数并避免重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23304235/