JavaScript中this详解(待补充详细例子,框架分类已完成)

367 阅读2分钟

参考文献

es5中,非箭头函数

this 永远指向最后调用它的那个对象。为『动态』

全局环境下的this

注意严格模式use strict区别

上下文对象中的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,而非执行时。为『静态』

原理

箭头函数没有自己的this,自己内部的this指向外部this

  • 不可以用作构造函数,不可以使用new命令
  • 不可以使用arguments对象
  • 不可以使用yield命令,不能用作Generator函数

不适合场景

  • 定义对象内的方法

针对此例说明:1、对象不构成单独的作用域,因为jump是箭头函数,故定义时候作用域就是全局;2、如果使用正常function定义,this随着使用cat.jump确定

  • 需要动态this时候

this优先级相关

  • 显示绑定:call,apply,bind,new,箭头函数绑定 箭头函数>new>call,apply,bind
  • 隐式绑定:根据调用关系确定的this

相关需要注意的知识点

  • let const不会提升变量,且不会绑定到window上去
  • 对象不够成单独的作用域,因为对象中的方法在定义时候属于全局作用域的