我如何实现像jQuery一样的链式模式? [英] How do I implement a Chaining Pattern like jQuery does?

查看:96
本文介绍了我如何实现像jQuery一样的链式模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建一个像jQuery使用的前缀?例如,在jQuery中我可以使用:

  $(。footer)。css('display','none' ); 

我想启用类似的语法,如下所示:

  google('。footer')。chrome('display','none'); 

我已经搜索了Google的答案,但找不到它。

解决方案

您有详细的解释此处



但实施的正确方法是show bellow:

  var google = function(valor){
var lalala ='3';

this.chrome = function(valor){
console.log(lalala +''+ valor);
返回此;
}

this.firefox = function(valor){
console.log(lalala +''+ valor);
返回此;
}

console.log(valor);

返回这个;
};

console.log('first call');
google('testando')。chrome('stack');

console.log('second call');
google('testando')。chrome('stack')。firefox('test');

正如您所看到的,关键是返回对象本身功能。

您可以看到实时代码在jsbin.com


How do I create a prefix like the one jQuery uses? For example, in jQuery I can use:

$(".footer").css('display', 'none');

and I'd like to enable a similar syntax, like this:

google('.footer').chrome('display', 'none');

I have searched Google for an answer, but couldn't find it.

解决方案

You have a detailed explanation here

But the right way to implement is show bellow:

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');

As you could see the key is to return the object itself on each function.

You could see the live code at jsbin.com

这篇关于我如何实现像jQuery一样的链式模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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