问题描述
我不禁注意到jQuery的源代码中有两个看似无用的函数(对于v1.9.1,它的第2702行和第2706行):
I can't help but notice there are two seemingly useless functions in the source code of jQuery (For v1.9.1, it's line 2702 and line 2706):
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
在jQuery中经常调用它们。有没有理由说他们不能简单地用布尔 true
或 false
替换函数调用?
Which both are called quite often within jQuery. Is there a reason why they don't simply substitute the function call with a boolean true
or false
?
推荐答案
它的使用方式如下:
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
此处 isImmediatePropagationStopped
是查询方法。像这样使用 event.isImmediatePropagationStopped()
here isImmediatePropagationStopped
is a query method. used like this event.isImmediatePropagationStopped()
当然,你可以定义一个实例方法,如:
of course, you can define a instance method, like:
event.prototyoe.isImmediatePropagationStopped = function() { return this._isImmediatePropagationStopped };
stopImmediatePropagation: function() {
this._isImmediatePropagationStopped = true; //or false at other place.
this.stopPropagation();
}
但你必须引入一个新的实例属性 _isImmediatePropagationStopped
存储状态。
but you have to introduce a new instance property _isImmediatePropagationStopped
to store the status.
有了这个技巧,你可以在这里切断一堆实例属性for hold true / false status,比如 _isImmediatePropagationStopped
, _isDefaultPrevented
等。
with this trick, you can cut off bunch of instance properties for hold true/false status here, like _isImmediatePropagationStopped
, _isDefaultPrevented
etc.
因此,在我看来,这只是代码风格的问题,不是对或错。
so that, in my opinion, this is just a matter of code style, not right or wrong.
PS:事件的查询方法,如 isDefaultPrevented
, isPropagationStopped
, isImmediatePropagationStopped
在DOM事件级别3 sepc中定义。
PS: the query methods on event, like isDefaultPrevented
, isPropagationStopped
, isImmediatePropagationStopped
are defined in DOM event level 3 sepc.
spec:
这篇关于jQuery源代码中的returnTrue和returnFalse函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!