JavaScript - this脱坑指南

xiaoxiao2021-02-28  82

首先this是什么?  this就是对象 请看案例:

//nodejs环境中 console.log(this); //返回{} //浏览器环境 console.log(this); //返回windows对象

作用:动态指定当前对象,使用当前对象的方法 那么怎么使用this呢? js中的对象或者方法具有this作用域 那么this有什么坑呢?  由于js原先的特性,this的作用域是在执行的时候确定的,这样就会导致this指向不明确 请看坑(所谓的坑就是内层函数不能访问外层的this,一般发生在回调函数的时候):

var name="global"; var test={ name:"test", showName:function(){ console.log(this.name) }, showArrow:function(){ setInterval(() => {console.log(this.name)}, 1000); }, showFun:function(){ setInterval(function(){console.log(this.name)}, 1000); } } test.showFun(); //输出undefined test.showArrow(); //输出test

为什么输出undefined?  因为匿名函数中没有指定name,所以是undefined 解决方案: 一、使用es6中箭头函数 箭头函数中this:是在定义的时候确定的 实质: 箭头函数中根本没有this,它只会引用外层函数的this,也就是我们为了防止this指向不明确,经常采用的this赋值: var _self=this; 箭头函数相当于在内部采用了这一个策略,引用外层作用域

var bird={ name:'bird', speak:()=>{ //console.log(this); console.log("I am a "+this.name); } } var duck={ name:"duck", speak:function(){ console.log("I am a "+this.name); } } const type=(animal)=>{ if(typeof animal.speak == "function"){ animal.speak(); return true; } return false; } type(bird); type(duck);

输出结果为:

I am a undefined I am a duck

为什么呢?  因为箭头函数内部没有this,会向上寻找this,speak是一个函数,具有this,但是其this.name没有赋值,所以是undefined。 也就是       箭头函数寻找,最近的具有this作用域的对象

因为箭头函数内部没有this,我们在箭头函数内部打印出来,

{}

可以看到是一个对象 二、使用bind,显式指定this作用对象

转载请注明原文地址: https://www.6miu.com/read-82457.html

最新回复(0)