this指向
-
在浏览器环境this指向window、nodeJs环境下this指向global
function bar(){console.log(this)} window.bar() //window -
方法调用中谁调用this指向谁
const person={run(){console.log(this)} } person.run() //person调用了run this指向了person //事件绑定 btn.addEventListener(type,function(){console.log(this)}) //this指向btn -
箭头函数的this指向父级作用域this
-
new可以改变改变this指向,this指向内存中实例对象
-
call、apply可以改变this的指向(了解)
-
call用法
-
所有函数中内置了call函数
-
call函数动态指定了当前函数调用权利
-
格式:fn.call(ObjectTarget,实参1,实参2,…)
const obj={name:'wt'} function fn(a){console.log(${this.name} is ${a})} fn.call(obj,'good') -
主要作用:改变构造函数中this的指向
function Father(name,age){ this.name=name; this.age=age; } function Son(name,age){ Father(this,name,age) //给this赋值 } -
-
apply用法
- apply用法和call同
- apply调用格式:fn.apply(ObjectTarget,数组)
- 传递参数为数组时,可以直接使用apply
const arr = [2,4,9]; Math.max.apply(Math,arr) //没有使用this
-
bind用法
-
bind方法改变内部this指向,但不会立即调用函数,返回一个改变this指向和初始化参数构造的原函数拷贝
-
应用:如果有的函数不需要立即调用,但是又想改变这个函数内部指向 :按钮点击置灰,3s后开启
btn.click=function(e){ this.disable=true; setTimeout(fn.bind(this),3000) function fn(){ this.disable=false; } } //bind方法绑定 const o={name:'andy'} function fn(){console.log(this.name)} const fCopy=fn.bind(o) -
-
本文介绍了JavaScript中this的关键概念,包括在不同环境下的指向(浏览器环境为window,Node.js环境为global),函数调用方式如何影响this(如方法调用、事件绑定),以及箭头函数的特殊性。同时,详细讲解了call、apply和bind方法,它们分别用于动态指定函数调用的对象,以及改变this的指向和预设参数。
1247

被折叠的 条评论
为什么被折叠?



