使用javascript链接的方法不起作用?

Unk*_*own 2 javascript

我试图让方法链使用javascript工作:

(function(){
    var first = function(){
        console.log("1st Chain");
        return this;
    };

    var second = function(){
        console.log("2nd Chain");
    }

    first().second();
})();
Run Code Online (Sandbox Code Playgroud)

只有第一个功能是打印到控制台,但第二个功能是说它未定义.但是,当我使用构造函数尝试它时,它的工作原理.

var Chaining = function(){
   this.first = function(){
       console.log("1st Chain");
       return this;
   };

   this.second = function(){
       console.log("2nd Chain");
   };
};

var chain = new Chaining;
chain.first().second(); // this works fine.
Run Code Online (Sandbox Code Playgroud)

pce*_*pce 6

在第一个链this中绑定到窗口,因此second不可见(undefined在该范围内).

(function(){

    var first = function(){
        console.log("1st Chain");
        console.log(this);
        return this;
    };

    window.second = function(){
        console.log("2nd Chain");
    }

    first().second();
})();
Run Code Online (Sandbox Code Playgroud)

要摆脱导出到第二个函数的全局窗口对象,可以使用仅在匿名函数的作用域中可见的对象.

(function(){

    var Chain = {};

    Chain.first = function(){
        console.log("1st Chain");
        console.log(this);
        return this;
    };

    Chain.second = function(){
        console.log("2nd Chain");
        return this;
    }

    // example
    Chain.first().second().first();

    // example export 
    // window.Chain = Chain;

})();
Run Code Online (Sandbox Code Playgroud)

如果你想链接到另一个范围,你可以导出你Chain的窗口并使用它没有新的,即.Chain.first().second();.

您还可以保存指向此的指针(如Jonathon所指出的):

(function(){

    var self = this;

    this.first = function(){
        console.log("1st Chain");
        console.log(this);
        return self;
    };

    this.second = function(){
        console.log("2nd Chain");
        return self;
    }

    // example
    first().second().first();

    // export example
    // window.Chain = self;
})();

// exported anonymous function to Chain    
// Chain.first().second();
Run Code Online (Sandbox Code Playgroud)

this有时需要保存指针,因为this关键字是范围更改并且引用已执行函数的上下文. this没有引用对象的实例,在哪里this使用,就像你在Java中所期望的那样.

因此,每个函数都可以绑定到另一个范围 要调整函数上下文,请使用bind,apply和call.