JavaScript学习笔记—函数中的this

this

  • 函数在执行时,JS解析器每次都会传递进一个隐含的参数,即this
  • this会指向一个对象,所指向的对象会根据函数调用方式的不同而不同
    (1)以函数形式调用时,this指向的是window
    (2)以方法的形式调用时,this指向的是调用方法的对象
    (3)构造函数中,this是调用方法的对象
    (4)箭头函数没有自己的this,由外层作用域决定
    (5)通过call和apply调用的函数,他们第一个参数就是函数的this
    (6)通过bind返回的函数,this由bind第一个参数决定(无法修改)
  • 通过this可以在方法中引用调用方法的对象
function fn(){
  console.log(this === window); // true
  console.log("fn打印", this); // fn打印,window
}
fn();

function fn2(){
  console.log("fn2打印", this);
}
const obj = {name:"孙悟空"};
obj.test = fn2;

const obj2 = {name:"猪八戒"};
obj.test(); // this为obj
obj2.test(); // this为obj2

const obj3 = {
  name:"沙和尚",
  sayHello: function(){
    console.log(this.name);
  }
};
const obj4 = {
  name:"唐僧",
  sayHello: function(){
    console.log(this.name);
  }
};
obj3.sayHello(); // 沙和尚
obj4.sayHello(); // 唐僧

箭头函数的this:
  箭头函数没有自己的this,它的this由外层作用域决定,箭头函数的this和它的调用方式无关

function fn(){
  console.log("fn -->", this);
}
const fn2 = () => {
  console.log("fn2 -->", this);
};
const obj = {
  name:"孙悟空",
  fn, // 属性名和函数名一样可以省略直接写属性名
  fn2, // 属性名和变量名一样时可以省略直接写属性名
  sayHello(){ // 可以省略function,直接方法名
    console.log(this); // obj
    function t(){
	  console.log("t -->", this);
	}
	t(); // t -->, window (以函数形式调用时,this指向的是window)
	const t2 = () => {
	  console.log("t2 -->", this);
	}
	t2(); // t2 -->, obj(箭头函数没有自己的this,它的this由外层作用域决定)
  }
};
obj.fn(); // this -->, obj
obj.fn2(); // this -->, window

posted @ 2023-01-16 20:14  程序员张3  阅读(22)  评论(0编辑  收藏  举报