JavaScript中this詳解(待補充詳細例子,框架分類已完成)

參考文獻

es5中,非箭頭函數

this 永遠指向最後調用它的那個對象。爲『動態』前端

全局環境下的this

注意嚴格模式use strict區別es6

上下文對象中的this

bind/call/apply改變this的指向

手寫bind簡單實現

// ES5實現第一版bind 函數  
    Function.prototype.bind = Function.prototype.bind || function (context) {
        var me = this;
        var args = Array.prototype.slice.call(arguments, 1);
        return function bound() {
            var innerArgs = Array.prototype.slice.call(arguments);
            var finalArgs = args.concat(innerArgs);
            return me.apply(context, finalArgs);
        }
    }
複製代碼

在學習這個時候,順便學習了這幾個題數組

// 貼下相關代碼
// 利用柯里化實現一個add方法
function add() {
        // 第一次執行時,定義一個數組專門用來存儲全部的參數
        var _args = Array.prototype.slice.call(arguments);

        // 在內部聲明一個函數,利用閉包的特性保存_args並收集全部的參數值
        var _adder = function () {
            _args.push(...arguments); // _args = _args.concat(Array.prototype.slice.call(arguments))
            return _adder;
        };

        // 利用toString隱式轉換的特性,當最後執行時隱式轉換,並計算最終的值返回
        _adder.toString = function () {
            return _args.reduce(function (a, b) {
                return a + b;
            });
        }
        return _adder;
    }


    add(1)(2) //3
    add(1)(2)(3) // 6
    add(1, 2, 3)(4) // 10
    add(1)(2)(3)(4)(5) // 15
    add(2, 6)(1)  // 9
複製代碼

構造函數和this

es6中,箭頭函數

箭頭函數的 this 始終指向函數定義時的 this,而非執行時。爲『靜態』bash

原理

箭頭函數沒有本身的this,本身內部的this指向外部this閉包

  • 不能夠用做構造函數,不能夠使用new命令
  • 不能夠使用arguments對象
  • 不能夠使用yield命令,不能用做Generator函數

不適合場景

  • 定義對象內的方法

針對此例說明:一、對象不構成單獨的做用域,由於jump是箭頭函數,故定義時候做用域就是全局;二、若是使用正常function定義,this隨着使用cat.jump肯定app

  • 須要動態this時候

this優先級相關

  • 顯示綁定:call,apply,bind,new,箭頭函數綁定 箭頭函數>new>call,apply,bind
  • 隱式綁定:根據調用關係肯定的this

相關須要注意的知識點

  • let const不會提高變量,且不會綁定到window上去
  • 對象不夠成單獨的做用域,由於對象中的方法在定義時候屬於全局做用域的
相關文章
相關標籤/搜索