this指向

this是什么

this是JavaScript语言的一个关键字。
它是函数运行时,在函数体内部自动生成的一个对象,只能在函数体内部使用。

函数内this指向

this的指向是在函数调用的时候决定的,调用方式不同决定了this指向不同,一般都指向调用者。

  1. 普通函数,this指向全局对象window window.fun();
//普通函数
function fn(){
    console.log(this); //window
 }
 window.fn();//window可以省略
  1. 对象内部函数的调用,this指向该对象 obj.fun();
//对象的方法
var obj = {
     sayHi:function(){
          console.log(this);//obj
     }
 }
obj.sayHi();
  1. 构造函数调用指向实例对象,原型对象里面的方法也指向实例对象。
 // 构造函数
        function Star(){
            this.fn = function(){
                console.log(this);
            }
        }
        Star.prototype.sing = function(){
            console.log(this);
        }
        var ldh = new Star();
        ldh.fn();
        ldh.sing();
  1. 事件绑定的函数指向绑定事件元素
  // 事件对象 
        var btn = document.querySelector("button")
        btn.onclick = function(){
            console.log(this); //button元素
        }
  1. 定时器函数和立即执行函数(IIFE)都是指向window对象
// 定时器
        setTimeout(function(){
            console.log(this);
        },1000)

        // 立即执行函数
        (function(){
            console.log(this);
        })()

改变this指向

常用的bind()、call()、apply()三种方法

call()
用于改变this指向,并调用函数

//函数.call(this指向,参数)

var obj = {}
function fun(a){
     console.log(this,a);
 }
 // 改变this指向
fun.call(obj,10);

call的主要作用可以实现继承

 // call继承
function Father (name,age){
   this.name = name;
   this.age = age;
}
function Son (name,age){
  //this 指向实例对象
   Father.call(this,name,age)
}
var son = new Son("ldh",20)
console.log(son); //Son {name: "ldh", age: 20}

apply()
调用函数且改变this指向 参数使用数组形式传递

  var obj = {}
        function fn(a){
            console.log(this,a);
        }
        fn.apply(obj,[10])

apply 主要应用 借助数学内置对象求最大值

 var arr = [1,99,23,45]
 var max = Math.max.apply(Math,arr)
 console.log(max);

bind()
改变this指向,不调用函数,返回原函数改变后产生的新函数

var obj = {}
        function fn(a){
            console.log(this,a);
        }
        var f = fn.bind(obj,10)
        f();

总结

相同点:

都可以改变函数内部this指向。

区别点:

  1. call 和 apply会调用函数,bind 不会调用函数。
  2. call 和 apply 传递参数不一样,call、bind 传递参数aru1,aru2形式,apply 必须数组形式。

主要应用场景:

  1. call 经常做继承。
  2. apply 经常跟数组有关,比如借助于数学对象实现数组最大值最小值。
  3. bind 经常改变定时器内部this指向。
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容