JavaScript方括号函数调用 [英] JavaScript square bracket function call

查看:151
本文介绍了JavaScript方括号函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我遇到这一行时浏览jQuery源代码:

Was browsing the jQuery source code when I met this line:

jQuery(this)[ state ? "show" : "hide" ]();

是否有任何优势

state ? jQuery(this).show() : jQuery(this).hide();

独立示例:

var object = {
    foo: function() {
        alert('foo');
    },

    bar: function() {
        alert('bar');
    }
};  


object[true ? 'foo' : 'bar']();
object[false ? 'foo' : 'bar']();


推荐答案

性能没有优势。但是如果你的函数中有很多参数,那么代码长度(如果你认为它是一个优势)和DRY原则(不要重复代码)是有优势的。

There's no advantage in performance. But there's an advantage in length of code (if you see it as an advantage), and DRY principle (don't repeat code) specially if you have many parameters in your functions.

考虑以下因素:

obj[ cond ? "foo" : "bar" ]("param1", "param2", "param3");

Versus:

cond ? obj.foo("param1", "param2", "param3") : obj.bar("param1", "param2", "param3");

如你所见,你以第二种方式重复很多代码

As you can see, you repeat 'a lot' of code in the second way

希望这会有所帮助。干杯

Hope this helps. Cheers

这篇关于JavaScript方括号函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆