JavaScript中this的指向问题

JavaScript中this的指向问题

1.默认绑定

没有被明确隶属对象执行的函数的this指向window

console.log(this)	//这里的this指向window

2.隐式绑定

被明确隶属对象执行的函数的this,指向执行对象

btn.onclick = function(){
console.log(this)		//这里的this指向btn
}

2.1.隐式丢失

如果作为参数,传到另一个函数中,那么丢失原本的对象,变成window

var obj = {
		name : "Admin",
		fn :function(){
			console.log(this)
		}
	}
	 obj.fn()		//这里的this指向obj
	
	  function newFn(a){
		a()
	} 
	newFn(obj.fn)	//这里的this指向window

但是,要注意:不是所有的回调函数中的this都指向window,某些特殊情况下,被系统修改了

   document.addEventListener("click",function(){
        console.log(this)            //这里的this指向document
    })
    obox.addEventListener("click",function(){
        console.log(this)            //这里的this指向obox
    })

3.强制绑定

利用函数的方法 call , apply , bind,改成谁,this就是谁。此方法修复了隐式丢失

call方法的使用方式


function fn(a,b){
         console.log(this); 	//String {"hello"}
         console.log(a);		//world
         console.log(b);		//123
     }
     var res = fn.call("hello","world",123);

总结:call方法可以接收多个参数但接收的第一个参数为this的内容,必须是对象,如果不是,强行转成对象 但是依然符合之前数据类型的使用规则

4.new绑定

函数被new执行后,函数内部的this会指向,new出来的实例对象

 function createPerson(n,a,s){
         this.name = n;
         this.age = a;
         this.sex = s;
        this.sayHello = function(){
             console.log(this.name + "---" + this.age+ "---" + this.sex);
         }
    }
    //以上函数体内部的所有this都指向实列对象p1
     var p1 = new createPerson("张三",18,"男");
     p1.sayHello();			//张三---18---男
发布了2 篇原创文章 · 获赞 6 · 访问量 110

猜你喜欢

转载自blog.csdn.net/fate_flower/article/details/104644832