js 对于链式加载的思考

常规的思考

A().B().C();

那么 可以调用B方法依赖于 A()的返回值 即 A返回的对象有B方法属性

ES6的proxy出现

先看一段代码 

var list = function(v) {
    var funstack = [];
    var tem = new Proxy({}, {
        get: function(obj, key, to) {
            if (key !== "get") {
                funstack.push(window[key]);
                return to;
            } else {
                return funstack.reduce((i, j, a) => {
                    return j(i);
                }, v);
            }
        }
    });
    return tem;
}
var double = n => n * 2;
var pow = n => n * n;
console.log(list(3).double.pow.get);

是不是很神奇 链式加载 这个也可以叫做懒加载 (是不是有一个 很重要的名词 )promise 

于是用Proxy重写了promise的简单方法 

var myPromise = function(callback) {
    var me = this;
    me.flag = 0;
    me.no=false;
    me.thenarr = [];
    setTimeout(callback.bind(me, function(r) {
        me.result = r;
        me.flag = 1;
    }, function() {
        me.flag = -1;
    }), 0);
}
myPromise.prototype = {
    constructor: myPromise,
    then: function(callback) {
        var me = this;
        callback.call(me, me.result);
    }
};
var tem = new myPromise(function(r1, r2) {
    setTimeout(r1.bind(this, "1211212"), 2000);
});
var t = tem;
tem.then = new Proxy(tem.then, {
    apply: function(t, k, args) {
        var me = this;
        if (!tem.no) {
            tem.thenarr=args[0];
            return;
        }
        return Reflect.apply(...arguments);
    }
});
Object.defineProperty(tem, "flag", {
    set: function(v) {
        t[v] = v;
        tem.no = true;
        tem.then(tem.thenarr);
    }
})
tem.then(function(r) {
    console.log(r);
})

使用thenarr来保存 then的参数 就是函数 调用的时候我判断 promise的标记物 保存 然后 当异步出现之后 加了一个触发器 就链式调用了then函数 同时传入参数