会网站开发维护的ps什么岗位,做推送好用的网站,网站后台管理教程,网站制作培训js中改变this指向的三种方式 1、call方法2、apply方法3、bind方法 1、call方法
使用 call 方法调用函数#xff0c;同时指定函数中 this 的值#xff0c;使用方法如下代码所示#xff1a;
scriptconst obj {uname: 刘德华}function fn(x, y) {console.log(this) … js中改变this指向的三种方式 1、call方法2、apply方法3、bind方法 1、call方法
使用 call 方法调用函数同时指定函数中 this 的值使用方法如下代码所示
scriptconst obj {uname: 刘德华}function fn(x, y) {console.log(this) console.log(x y)}// 1. 调用函数 // 2. 改变 this 指向fn.call(obj, 1, 2)
/script运行结果如下 总结
call 方法能够在调用函数的同时指定 this 的值使用 call 方法调用函数时第1个参数为 this 指定的值call 方法的其余参数会依次自动传入函数做为函数的参数
2、apply方法
使用 call 方法调用函数同时指定函数中 this 的值使用方法如下代码所示
scriptconst obj {age: 18}function fn(x, y) {console.log(this) // {age: 18}console.log(x y)}// 1. 调用函数// 2. 改变this指向 // fn.apply(this指向谁, 数组参数)fn.apply(obj, [1, 2])// 3. 返回值 本身就是在调用函数所以返回值就是函数的返回值// 使用场景 求数组最大值// const max Math.max(1, 2, 3)// console.log(max)const arr [100, 44, 77]const max Math.max.apply(Math, arr)const min Math.min.apply(null, arr)console.log(max, min)// 使用场景 求数组最大值console.log(Math.max(...arr))
/script运行结果如下 总结
apply 方法能够在调用函数的同时指定 this 的值使用 apply 方法调用函数时第1个参数为 this 指定的值apply 方法第2个参数为数组数组的单元值依次自动传入函数做为函数的参数
3、bind方法
bind 方法并不会调用函数而是创建一个指定了 this 值的新函数使用方法如下代码所示
scriptconst obj {age: 18}function fn() {console.log(this)}// 1. bind 不会调用函数 // 2. 能改变this指向// 3. 返回值是个函数 但是这个函数里面的this是更改过的objconst fun fn.bind(obj)// console.log(fun) fun()// 需求有一个按钮点击里面就禁用2秒钟之后开启document.querySelector(button).addEventListener(click, function () {// 禁用按钮this.disabled truewindow.setTimeout(function () {// 在这个普通函数里面我们要this由原来的window 改为 btnthis.disabled false}.bind(this), 2000) // 这里的this 和 btn 一样})
/script运行结果如下 注bind 方法创建新的函数与原函数的唯一的变化是改变了 this 的值。