1. 程式人生 > >apply bind call 和 this

apply bind call 和 this

方式 hat nbsp wrap http AR function TE true

Javascript裏面的this由調用方式確定它的指向。

1. 函數

此時為this為window

        function log()
        {
            console.log(this);
        }
        log();

技術分享圖片

2. 對象方法

此時為實例對象。

        function log()
        {
            console.log(this);
        }

        function class1()
        {
            this.name="class1 name"
        }

        var obj1=new class1();
        obj1.fu1=log;
        obj1.fu1();

技術分享圖片

但我們可以通過使用apply,bind,call來指定‘this‘.

        function log()
        {
            console.log(this);
        }
        log.call({name:"test call"});
        log.apply({name:"test apply"});
        log.bind({name:"test bind"})()

技術分享圖片

下面是一個簡單的bind實現,可以幫助理解。

        Function.prototype.bind2 = function(context){
            var _that = this;
            return function()
            {
                _that.apply(context);
            };
        }

        function fn1()
        {
            console.log(this);
        }

        var fn2=fn1.bind2({name:"testing"});
        fn2();

技術分享圖片

apply bind call 和 this