• 浅谈JavaScript中this的指向


    浅谈JavaScript中this的指向

    1.默认指向,this默认指向的是window对象

    console.log(this);//打印的是window
    

    2.函数调用时

    2.1独立调用,this指向window对象
    function test(){
        console.log(this);//打印的是window
    }
    window.test();//简写test()
    
    2.2函数作为某个对象的方法时,this指向的是当前对象
    let obj = {
         name:"test",
         show:function(){
         console.log(this);//这个打印出来的是window
    	}
    }
    let a = obj.show;//a就是function(){console.log(this);}
    a();//window.a();
    

    3.指向当前对象

    let obj = {
       name:'test',
       age:19,
       show:function(){
        console.log(this);
        }
    }
    obj.show();//打印出来的是Object
    

    4.this指向绑定的元素,当函数作为一个事件处理函数的时候,这时this是指向绑定的元素

    <body>
    	<button>点击</button>
    </body>
    <script>
    	document.querySelector("button").onclick=function(){
    	console.log(this);
    	}
    </script>
    

    5.改变this的指向

    5.1 call()
    let obj={
        name:'hello',
        age:19,
        show:function(x,y){
            console.log(this);//Object
            console.log(this.name);//张三
            console.log(this.age+x+y);//50
        }
    }
    let obj2={
        name:'张三',
        age:30
    }
    obj.show.call(obj2,10,10);
    
    5.2 apply()
    let obj={
        name:'hello',
        age:19,
        show:function(x,y){
            console.log(this);//Object
            console.log(this.name);//张三
            console.log(this.age+x+y);//60
        }
    }
    let obj2={
        name:'张三',
        age:30
    }
    obj.show.apply(obj2,[10,20]);
    
    es5中bind()
    let obj={
        name:'hello',
        age:19,
        show:function(x,y){
            console.log(this);//Object
            console.log(this.name);//张三
            console.log(this.age+x+y);//60
        }
    }
    let obj2={
        name:'张三',
        age:30
    }
    let test = obj.show.bind(obj2);
    test(10,20);
    

    6.箭头函数的this的指向,它的this指向始终是指向的外层作用域

    由于箭头函数不绑定this, 它会捕获其所在(即定义的位置)上下文的this值, 作为自己的this值
    let obj = {
        name:"test",
        show:()=>{
            console.log(this);//打印出Window
        }
    }
    obj.show();
    
  • 相关阅读:
    Python-22-并发编程
    hadoop学习记录(二)HDFS java api
    hadoop学习记录(一)HDFS
    hadoop学习记录(零)
    android 下载instagram动态中图片的demo
    android 使用<merge>标签
    利用dijkstra算法规划线路
    Android Studio如何引用外部Library工程
    设计模式(二):单例模式
    设计模式(一):设计模式入门
  • 原文地址:https://www.cnblogs.com/Wardenclyffe/p/12565760.html
Copyright © 2020-2023  润新知