当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 芝士蒸梨(三):JavaScript的this指向

芝士蒸梨(三):JavaScript的this指向

2020年07月22日  | 移动技术网IT编程  | 我要评论

芝士蒸梨(三):JavaScript的this指向

核心:谁调用函数,this就指向谁

  • 普通函数调用:

    this指向window

let a = "ych";
function af( ) { 
 alert( this.a ); 
}
af( );// undefined

var b = "ych";
function bf( ) { 
 alert( this.b ); 
}
bf( );// ych

window.c = "ych";
function cf( ) { 
 alert( this.c ); 
}
cf( );// ych
  • 对象函数调用:

    this指向调用函数的对象

let obj1={
  a:111
};
let obj2={
  a:222,
  	fn:function(){
   	alert(this.a);
  	}
};

obj2.fn(); // 222
obj1.fn=obj2.fn; // obj1首先创建fn,再将obj2函数体传入
obj1.fn(); // 111,this指向调用者 obj1
  • 构造函数调用
let Obj = function() {
 this.name = 'ych';
}

let obj = new Obj();
console.log(obj.name); // ych
  • 箭头函数调用
window.a = 222;
let obj={
  	a:111,
  	fn1:function(){  
    	setTimeout(()=>{console.log(this.a)}); // this指向obj
	},
  	fn2:function(){  
   		setTimeout(function(){console.log(this.a)}); // this指向window
  	}
};

obj.fn1(); // 111
obj.fn2(); // 222
  • call / apply

主要用途:改变this指向方法借用

  • call:接受参数不固定,第一个是函数体内this的指向,之后是依次传入的参数
  • apply:接受两个参数,第一个是函数体内this的指向第二个是一个集合对象
let fn=function(a,b,c){ console.log(a,b,c); }
let arr=[1,2,3];
fn.call(window, arr[0],arr[1],arr[0]); // 1 2 1
fn.call(window, arr,arr[1]); // [1,2,3] 2 undefined
fn.apply(window, arr); // 1 2 3

let obj1={
  a:222
};

let obj2={
  	a:111,
  	fn:function(){
    alert(this.a);
  	}
}
obj2.fn.call(obj1); // 222

本文地址:https://blog.csdn.net/weixin_46363226/article/details/107460583

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网