• this指向


    执行期上下文

    函数执行时(准确来说,是在函数发生预编译的前一刻),会创建一个执行期上下文的内部对象。一个执行期上下文定义了一个函数执行时的环境。

    每调用一次函数,就会创建一个新的上下文对象,他们之间是相互独立且独一无二的。当函数执行完毕,它所产生的执行期上下文会被销毁。

    参考链接:https://www.cnblogs.com/chenyingjie1207/p/9966036.html

    this

    解析器在调用函数每次都会向函数内部传递进一个隐含的参数,这个隐含的参数就是 this,this 指向的是一个对象,这个对象我们称为函数执行的 上下文对象。

    函数内 this 的指向【非常重要】

    我们在《JavaScript 基础/函数.md》这篇文章讲过,函数的调用有六种形式。

    根据函数的调用方式的不同,this 会指向不同的对象:

    • 1.以函数的形式(包括普通函数、定时器函数、立即执行函数)调用时,this 的指向永远都是 window。比如fun();相当于window.fun();
    • 2.以方法的形式调用时,this 指向调用方法的那个对象
    • 3.以构造函数的形式调用时,this 指向实例对象
    • 4.以事件绑定函数的形式调用时,this 指向绑定事件的对象
    • 5.使用 call 和 apply 调用时,this 指向指定的那个对象
    • 6.ES6 中的箭头函数并不会使用上面的准则,而是会继承外层函数调用的 this 绑定(无论 this 绑定到什么)。

    针对第 1 条的举例

    fun()
    var a = 10
    function fun(){
        
        console.log(this.a)
        console.log(this) //window  ----1
    }
    (function(){
        console.log(this)//window   ----1
    })()
    

    第 2 条的举例

    var obj1 = {
        name: 'smyh',
        sayName: function(){
            console.log(this.name)
            console.log(this) //obj1 -----2
        }
    };
    obj1.sayName()
    

    第 3 条的举例

    //构造函数
    function FunObj(){
      console.log(this)
    }
    var obj = new FunObj() //obj实例  Object构造函数 ---3
    

    第 4 条的举例

    <button onclick="myfun(this)">点击</button>
    
    function myfun(o){
       console.log(o) //button   -----4
    }
    
    

    第 5条的举例

    function demofun(obj){
    	console.log(this) //person -----5
    }
    var person = {
        name: '李四',
        age: 23
    }
    demofun.call(person)
    

    箭头函数中 this 的指向

    ES6 中的箭头函数并不会使用上面的准则,而是会继承外层函数调用的 this 绑定(无论 this 绑定到什么)。

    		// var arr = [1, 2, 3, 4, 5]
    		// var newArr = arr.sort((a,b) => {
    		// 	console.log(this)  //父类是window
    		// 	/*
    		// 		1.箭头函数没有本身的this
    		// 		this 是继承父类的this
    
    		// 	*/
    		// 	return a - b
    		// })
    
    
    		var obj2 = {
    		    name: 'smyh',
    		    sayName: function(){
    		    	//console.log(this) //obj2
    		    	var arr = [1,2]
    				var newArr = arr.sort((a,b) => {
    					console.log(this)  //父类是obj2
    					return a - b
    				})
    		    }
    		};
    		obj2.sayName()
    

    改变函数内部的 this 指向

    JS 专门为我们提供了一些方法来改变函数内部的 this 指向。详见下一篇文章中的 call()、apply()、bind() 方法。

  • 相关阅读:
    [主席树][学习笔记]
    [bzoj2588][ Count on a tree]
    [bzoj3524][Couriers]
    [luogu3834][可持久化线段树 1(主席树)]
    [luogu3810][bzoj3262][陌上花开]
    [树套树][学习笔记]
    [luogu4556][Vani有约会]
    [线段树合并][学习笔记]
    [hdu6183][Color it]
    [动态开点线段树][学习笔记]
  • 原文地址:https://www.cnblogs.com/yuanliy/p/14551263.html
Copyright © 2020-2023  润新知