this 是 JS 中一个难点, 通常来讲, this 就是指向当前的运行环境, JS 对象可以看成全局对象和局部对象, 当函数直接在全局环境中运行, 则 this 指向全局对象
- function foo()
- {
- console.log(this);
- }
- foo();// 输出 Windows
第二种, 当 this 在对象中的时候, this 指向的是该对象
- var obj ={
- name :"Jack",
- value :"can play pubg",
- play : function(){
- console.log(this.name + this.value)
- }
- };
- obj.play(); // 输出 Jack can play pubg
第三种, 当 this 在构造函数中的时候, this 将会指向新的实例, 此时 this 会通过 new 关键字指向实例, 详细的下回开专题讲
- function Foo(name,value){
- this.name = name;
- this.value = value;
- this.play = function(){
- console.log(this.name + this.value);
- }
- }
- var foo = new Foo("peter","can do it");
- foo.play();// 输出 Peter can do it
第四种, 当 this 被 apply 和 call 以及 bind 函数使用时 会改变当前的运行环境
- let a =5;
- let b =3;
- let sub =(a,b) => a - b;
- let add =(a,b) => a + b;
- console.log(sub.call(add,a,b)); // 改变 add 的运行环境 输出为 2
this 关键字在写插件时尤其重要, 一定要反复理解
来源: https://www.cnblogs.com/maoxiaodun/p/9995648.html