this指向问题(1)

tech2022-08-26  114

一、构造函数中的this

// 1.普通构造函数的方法调用,this指向当前创建的实例化对象 function Person(name, age) { this.name = name; this.age = age; this.say = function () { console.log(this.name); //linlin this指向当前实例化出来的的对象 console.log(this); //Person { name: 'linlin', age: 18, say: [Function] } } } let per = new Person("linlin", 18); per.say();

三、定时器函数中的this【指向定时器本身-如何解决看下面的解释】

//在say函数里面放一个定时器函数,定时器的作用是隔了1s就执行第一个参数-函数体。 //相当于是定时器调用这个函数体,是setTimeout去调用它,所以第一个参数函数体里面的this指向setTimeout function Person(name, age) { this.name = name; this.age = age; this.say = function () { setTimeout(function () { console.log(this.name); //undefined console.log(this); //this指向setTimeout }, 1000); } } let per = new Person("linlin", 18); per.say();

如何解决this指向问题:

1、【定义一个变量_this存放this,在setTimeout里面使用这个变量_this】

function Person(name, age) { this.name = name; this.age = age; this.say = function () { var _this = this; setTimeout(function () { console.log(_this.name); //linlin }, 1000); } } let per = new Person("linlin", 18); per.say();

2、使用箭头函数,箭头函数没有自己的作用域,会指向外层作用域。

function Person(name, age) { this.name = name; this.age = age; this.say = function () { //这里使用箭头函数,this指向了外层作用域,也就是指向了Person构造出来的实例对象。 setTimeout(() => { console.log(this.name); //linlin }, 1000); } } let per = new Person("linlin", 19); per.say();

四、不适用于箭头函数的场景

字面量写法的对象中不建议用箭头函数。因为箭头函数的this指向外层作用域,而obj是一个对象,没有作用域。

//(1)字面量对象中的普通函数 let obj = { name: "zs", age: 18, say: function () { console.log(this.name); //zs } } //obj对象调用了say方法,this指向了obj,所以this指向obj obj.say(); //(2)字面量对象中使用了箭头函数,this指向外层作用域,但是obj无法产生作用域,也就是this实际指向了window。 var name= 'ls; var obj = { name: ‘zs’, age: 18, say: ()={ console.log(this.name); //ls } } obj.say();
最新回复(0)