【发布时间】: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());
这里的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