3

怎样用 if(或其他更清晰的)语句代替下面这行短路求值(&&和||)的代码?

 3 years ago
source link: https://www.v2ex.com/t/791368
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  JavaScript

怎样用 if(或其他更清晰的)语句代替下面这行短路求值(&&和||)的代码?

  manyfreebug · 1 天前 · 597 次点击

源码在: https://github.com/rickharrison/validate.js/blob/master/validate.js#L126

var _onsubmit = this.form.onsubmit;

this.form.onsubmit = (function(that) {
    return function(evt) {
        try {
            return that._validateForm(evt) && (_onsubmit === undefined || _onsubmit());
        } catch(e) {}
    };
})(this);
其中这行代码, 作者想表达的意思是什么?
return that._validateForm(evt) && (_onsubmit === undefined || _onsubmit())

怎样用 if(或其他更清晰的)语句代替下面这行短路求值(&&和||)的代码?:

return that._validateForm(evt) && (_onsubmit === undefined || _onsubmit());
that._validateForm(evt) 上半段代码似乎总是会执行
(_onsubmit === undefined || _onsubmit())
等价于:
if(_onsubmit) {
    _onsubmit();
}
这半段代码, 作者想表达的意思似乎是: 如果在 form 元素上添加了 onsubmit 事件属性,则执行_onsubmit()回调函数


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK