相关疑难解决方法(0)

基本对象/函数链如何在javascript中工作?

我正试图让jQuery风格的函数链接在我的脑海中.我的意思是:

var e = f1('test').f2().f3();
Run Code Online (Sandbox Code Playgroud)

我有一个例子可以工作,而另一个没有.我会发布以下内容.我总是想学习第一个原理的基本原理,以便我可以在它之上构建.到目前为止,我对链接的工作方式只有一个粗略而宽松的理解,而且我遇到了一些我无法智能排除故障的错误.

我知道的:

  1. 函数必须返回自己,又称"返回此";
  2. 可链接函数必须驻留在父函数中,也就是在jQuery中.css()是jQuery()的子方法,因此jQuery().css();
  3. 父函数应该返回自身或自身的新实例.

这个例子有效:

var one = function(num){
    this.oldnum = num;

    this.add = function(){
        this.oldnum++;
        return this;
    }

    if(this instanceof one){
        return this.one;    
    }else{
        return new one(num);    
    }
}
var test = one(1).add().add();
Run Code Online (Sandbox Code Playgroud)

但是这个没有:

var gmap = function(){

    this.add = function(){
        alert('add');

        return this;    
    }   

    if(this instanceof gmap) {
        return this.gmap;   
    } else{
        return new gmap();  
    }

}
var test = gmap.add();
Run Code Online (Sandbox Code Playgroud)

javascript methods method-chaining chaining

26
推荐指数
1
解决办法
3万
查看次数

标签 统计

chaining ×1

javascript ×1

method-chaining ×1

methods ×1