javascript - 如何共享作为对象属性的函数并避免重复代码

标签 javascript jquery oop module prototypal-inheritance

我有一个看起来像这样的对象:

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());

Live example.

这里的 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/

相关文章:

javascript - 如何查找字符串中两个字符之间的多个值 - JS

javascript - JavaScript 中的 Java 式 OOP 和 jQuery 失败

javascript - 如何用关键字替换文本?

javascript - 将 Javascript "Class"原型(prototype)复制到对象

jquery - 我应该如何在 Jquery Mobile 中使用 rel ="canonical"?

c# - 我有一个基类。如何为正确的派生类调用正确的方法?

c# - 访问子类中的私有(private)变量?

c# - 如何将服务器端属性值传递到 aspx 页面框架中加载的其他 htm 页面

javascript - 检查动态创建的数组中是否存在所选选项

javascript - 当元素在 jquery 中使用 .fadetoggle() 可见时,如何对其进行 .focus() ?