windows系统做ppt下载网站,网站搜索引擎优化教程,服装企业营销网站建设,关键词是什么意思✨什么是bind()
bind()的MDN地址 bind() 方法创建一个新函数#xff0c;当调用该新函数时#xff0c;它会调用原始函数并将其 this 关键字设置为给定的值#xff0c;同时#xff0c;还可以传入一系列指定的参数#xff0c;这些参数会插入到调用新函数时传入的参数的前面。…✨什么是bind()
bind()的MDN地址 bind() 方法创建一个新函数当调用该新函数时它会调用原始函数并将其 this 关键字设置为给定的值同时还可以传入一系列指定的参数这些参数会插入到调用新函数时传入的参数的前面。 call(),apply(),bind()的异同 相同点
三者都是动态的修改函数内部的this指向 不同点
传参方式不同call()和bind()是按照顺序传参apply()是通过数组/伪数组传参。执行机制不同call()和apply()是立即执行函数bind()不会立即执行函数而是会返回一个修改过this的新函数。 call()
函数名.call(修改后的this,形参1,形参2…) person {name: zhangsan}function fn (a, b,) {console.log(this) //{name: zhangsan}console.log(a, b) //1 2 console.log(a b) //3}//call 立即执行函数 没有返回值let res fn.call(person, 1, 2)console.log(res); //undefinedapply()
函数名.apply(修改后的this,数组/伪数组) person {name: zhangsan}function fn (a, b) {console.log(this) //{name: zhangsan}console.log(a, b) //1 2 console.log(a b) //3}//apply 立即执行函数 没有返回值let res fn.apply(person, [1, 2])console.log(res) //undefinedbind()
函数名.bind(修改后的this形参1,形参2…) person {name: zhangsan}function fn (a, b, c, d) {console.log(this) //{name: zhangsan}console.log(a, b, c, d) //1 2 3 4console.log(a b c d) //10}//bind 不会立即执行函数而是返回一个修改this的新函数let newFn fn.bind(person, 1, 2)newFn(3, 4)✨ 手写bind() :myBind()
可参照上一篇文章 手写call()
代码
Function.prototype.myBind function (thisArg, ...args) {return (...reArgs) {// this:原函数(原函数.myBind)return this.call(thisArg, ...args, ...reArgs)}}// ------------- 测试代码 -------------const person {name: zhangsan}function func(numA, numB, numC, numD) {console.log(this)console.log(numA, numB, numC, numD)return numA numB numC numD}const bindFunc func.myBind(person, 1, 2)const res bindFunc(3, 4)console.log(返回值:, res) 测试