提取方法的Javascript版本
我一直在读Ruby重构书(Fields,Harvie,Fowler)。他们提到了提取周围的方法操作,如果您有中间部分不同的方法,可以使用该操作来避免重复提取方法的Javascript版本,javascript,ruby,refactoring,Javascript,Ruby,Refactoring,我一直在读Ruby重构书(Fields,Harvie,Fowler)。他们提到了提取周围的方法操作,如果您有中间部分不同的方法,可以使用该操作来避免重复 def number_of_descendants_named(name) count_descendants_matchin { |descendant| descendant.name == name } end def number_of_living_descendants count_descendants_matching
def number_of_descendants_named(name)
count_descendants_matchin { |descendant| descendant.name == name }
end
def number_of_living_descendants
count_descendants_matching { |descendant| descendant.alive? }
end
def count_descendants_mathing(&block)
children.inject(0) do |count, child|
count += 1 if yield child
count + child.count_descendants_matching(&block)
end
end
我相信你明白了。您将如何使用Javascript进行类似操作 Javascript也有闭包,所以很简单,只需将块转换为匿名函数,代码实际上是相同的:
var number_of_descendants_named = function(name) {
return count_descendants_matching(function(descendant) {
return descendant.name == name;
});
};
var number_of_living_descendants = function(descendant) {
return count_descendants_matching(function(descendant) {
return descendant.alive();
});
};
var count_descendants_mathing = function(cb) {
// reduce: use underscore or any other functional library
return somelib.reduce(children, 0, function(count, child) {
return count + (cb(child) ? 1 : 0) + child.count_descendants_matching(cb)
});
};
这种所有内容都是要返回的表达式的函数式在普通Javascript中非常冗长,但一些altJS语言(例如Coffeescript)将其简化了很多。Javascript也有闭包,因此非常简单,只需将块转换为匿名函数,代码实际上是相同的:
var number_of_descendants_named = function(name) {
return count_descendants_matching(function(descendant) {
return descendant.name == name;
});
};
var number_of_living_descendants = function(descendant) {
return count_descendants_matching(function(descendant) {
return descendant.alive();
});
};
var count_descendants_mathing = function(cb) {
// reduce: use underscore or any other functional library
return somelib.reduce(children, 0, function(count, child) {
return count + (cb(child) ? 1 : 0) + child.count_descendants_matching(cb)
});
};
在普通Javascript中,所有内容都是要返回的表达式的函数式非常冗长,但是一些altJS语言(例如Coffeescript)将其简化了很多。感谢您的快速回答!那正是我要找的!谢谢你的快速回答!那正是我要找的!