首页 > js如何实现函数的连续调用

js如何实现函数的连续调用

比如我在写自定义过滤的时候使用这样的语法

var filters = angular.module('filters', []);
filters.filter('quality', function() {
    
}).filter('level', function() {
    
}).filter('RMB', function() {
   
}).filter('button', function() {

});

请问如何定义实现类似
a().b().c()或者a().a().a()这样的调用


var a = {
    b: function() {
        console.log('b');
        return {
            c: function() {
                console.log('c');
                return {
                    d: function() {
                        console.log('d')
                    }
                }
            }
        }
    }
}
a.b().c().d()

链式调用一般都是从左往右依次运算,只要方法的返回值里面包含了下一个方法就没有问题吧。


非异步的链式调用

var obj = {};
    obj.func1 = function(){
        console.log('func1');
        return this;
    };
    obj.func2 = function(){
        console.log('func2');
        return this;
    };
    obj.func1().func2();

异步的链式调用(Promise)

function runFunc1(){
        var p = new Promise(function(resolve,reject){
            //异步操作
            setTimeout(function(){
                console.log('success runFunc1');
                resolve('数据1');
            },5000);
        });
        return p;
    }

    function runFunc2(){//如果promise没有运行在函数内部会立即执行
        var p = new Promise(function(resolve,reject){
            //异步操作
            setTimeout(function(){
                console.log('success runFunc2');
                resolve('数据2');
            },5000);
        });
        return p;
    }

    runFunc1()
    .then(function(data){
        console.log(data);
        return runFunc2();
    })
    .then(function(data){
        console.log(data);
    })

function MyObj(){

}
//调用后每次都返回对象自身,就可以实现链式调用
MyObj.prototype.do=function(){

    return this;
}

var myObj=new MyObj();
myObj.do().do().do();

var myObject=(function(){

    var self={
        do:function(){
            return self;
        }
    };
    return self;
}());

myObject.do().do().do();

function Demo()
{
    this.words = {};
}

Demo.prototype.setWord = function (man,word) 
{
    this.words[man] = word;
    return this;
};

Demo.prototype.say = function()
{
    console.log("hello world!");
    console.log(this.words);
};

(new Demo)
    .setWord("Ramsay Bolton","Wintefell is mine,come and see!")
    .setWord("Joffrey Baratheon","i am the king")
    .setWord("Sandor Clegane","fuck the king")
    .say();

试试看,主要是玩的还是心跳:

var test = function() {
    if (!(this instanceof test)) {
        return new test();
    }
};

test.prototype.a = function() {
    console.log('this is a');
    return this;
};

test.prototype.b = function() {
    console.log('this is b');
    return this;
};

test.prototype.c = function() {
    console.log('this is c');
    return this;
};

test()
    .a()
    .b()
    .c();
【热门文章】
【热门文章】