【问题标题】:How to share functions which are object properties and avoid duplicate code如何共享作为对象属性的函数并避免重复代码
【发布时间】:2014-04-25 22:38:00
【问题描述】:

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

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;
    }
} 

但不确定如何实际实现,这可能吗?

【问题讨论】:

  • 如果可以直接访问属性,是否需要doSomething函数?
  • @KimGysen 主要用于组织和某种封装。这也是一个过于简单的例子。
  • 嗯好的,只是想知道;因为属性不是私有的,你可以简单地做:return foo.parent.childOne.prop + foo.parent.childTwo.prop;,你就摆脱了 doSomething 重复......

标签: javascript jquery oop module prototypal-inheritance


【解决方案1】:

你仍然需要上下文绑定:

function something(context){
  return function(){
    return context.prop;
  }
}

现在:

doSomething: something(this);

现在,只需像在 foo.other.action 方法中那样调用 doSomething()

【讨论】:

  • 是的,这可能是一个合理的解决方案,现在功能太短,无法证明,如果功能变得更复杂,它可能是合理的。
【解决方案2】:

也许这样的事情可以让你摆脱一些重复的代码:

var foo = {
    parent: {
        doSomething: function() {
            return this.prop;
        },
        childOne: {
            prop: 1
        },
        childTwo: {
            prop: 2
        }
    },
    other: {
        action: function() {
            var fooPar = foo.parent;
            return fooPar.doSomething.call(fooPar.childOne) +
                   fooPar.doSomething.call(fooPar.childTwo);
        }
    }
}

演示:http://jsfiddle.net/YN7G6/5/

【讨论】:

  • 这是一个有趣的可能性,但这让我怀疑我是否有正确的方法。我的代码基于这个建议:css-tricks.com/…,它似乎有这个缺点。
【解决方案3】:

如果您只关心重复代码,您可以简单地分解函数。您的 this 已经处理绑定正确的上下文。

function bar() {
    return this.prop;
}

var foo = {
    parent: {
        childOne: {
            prop: 1,
            doSomething: bar
        },
        childTwo: {
            prop: 2,
            doSomething: bar
        }
    },
    other: {
        action: function() {
            return foo.parent.childOne.doSomething() +
                   foo.parent.childTwo.doSomething();
        }
    }
}

如果你想完全去掉多余的doSomething: bar,你也可以使用call方法显式绑定上下文。

var foo = {
    parent: {
        childOne: {
            prop: 1 
        },
        childTwo: {
            prop: 2
        }
    },
    other: {
        action: function(){
            return bar.call(foo.parent.childOne) +
                   bar.call(foo.parent.childTwo);
        }
    }
}

【讨论】:

  • 当然。神奇的一切都发生在您已经拥有的this 中。真正了解 this 是什么的好资源在这里:howtonode.org/what-is-this
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多