如何创建一个像 jQuery 使用的前缀?例如,在 jQuery 中我可以使用:
$(".footer").css('display', 'none');
我想启用类似的语法,如下所示:
google('.footer').chrome('display', 'none');
我已经在谷歌上搜索了答案,但找不到。
你有详细的解释here http://en.wikipedia.org/wiki/Method_chaining
但正确的实施方法如下所示:
var google = function(valor){
var lalala = '3';
this.chrome = function(valor){
console.log(lalala + ' ' + valor);
return this;
}
this.firefox = function(valor){
console.log(lalala + ' ' + valor);
return this;
}
console.log(valor);
return this;
};
console.log('first call');
google('testando').chrome('stack');
console.log('second call');
google('testando').chrome('stack').firefox('test');
正如你所看到的,关键是返回对象本身在每个功能上。
你可以看到jsbin.com 上的实时代码 http://jsbin.com/zipab/1/watch?js,console
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)