襄阳做网站公司中国设计之窗官方网站
news/
2025/9/26 18:47:43/
文章来源:
襄阳做网站公司,中国设计之窗官方网站,学校网站建设代码,网站建设优化过程中的优化策略对于 call / apply / bind 来说#xff0c;他们的首要目的是用于改变执行上下文的 this 指针。 call / apply 对 call / apply 的使用#xff0c;一般都如下#xff0c;用于改变执行环境的上下文。只是 call 接受的是一个一个的参数#xff0c;而 apply 则是接受的是一个参…对于 call / apply / bind 来说他们的首要目的是用于改变执行上下文的 this 指针。 call / apply 对 call / apply 的使用一般都如下用于改变执行环境的上下文。只是 call 接受的是一个一个的参数而 apply 则是接受的是一个参数数组。 const obj1 {a: 1,myFunc(var1) {console.log(this.a var1)}
}
const obj2 {a: 2
}const myFunc obj1.myFuncmyFunc(1) // NaN
obj1.myFunc(1) // 2
myFunc.call(obj2, 1) // 3
myFunc.apply(obj2, [1]) // 3 bind bind 是 ES2015 出的一个方法也是用于改变函数内部的 this 指向。但不一样的是bind 方法不是直接执行的而是生成一个新的已被改变过的函数。 const obj1 {a: 1,myFunc(var1) {console.log(this.a var1)}
}
const obj2 {a: 2
}const myFunc obj1.myFunc
const bindMyFunc1 myFunc.bind(obj1)
const bindMyFunc2 myFunc.bind(obj2)myFunc(1) // NaN
bindMyFunc1(1) // 2
bindMyFunc2(1) // 3 通过上面的例子就可以看出来bind 方法就可以生成一个新的 this 指向的 function。 手动写 bind 函数 仅仅作为简单实现的话我们仅需要注意改变 this 指向和预置参数即可。 function bind(fn, _this, ...args) {if(typeof fn ! function) {throw new Error(bind fn need to be function)}return function(...innerArgs) {return fn.apply(_this, [...args, ...innerArgs])}
} 当然这个手动实现的 bind 方法是只实现了最主要的功能对函数的原型链和作为构造函数的方式都是没有考虑到的。这里可以参考 MSDN 的 polyfill 方法。 if (!Function.prototype.bind) {Function.prototype.bind function(oThis) {if (typeof this ! function) {// closest thing possible to the ECMAScript 5// internal IsCallable functionthrow new TypeError(Function.prototype.bind - what is trying to be bound is not callable);}var aArgs Array.prototype.slice.call(arguments, 1),fToBind this,fNOP function() {},fBound function() {// this instanceof fBound true时,说明返回的fBound被当做new的构造函数调用return fToBind.apply(this instanceof fBound? this: oThis,// 获取调用时(fBound)的传参.bind 返回的函数入参往往是这么传递的aArgs.concat(Array.prototype.slice.call(arguments)));};// 维护原型关系if (this.prototype) {// Function.prototype doesnt have a prototype propertyfNOP.prototype this.prototype; }// 下行的代码使fBound.prototype是fNOP的实例,因此// 返回的fBound若作为new的构造函数,new生成的新对象作为this传入fBound,新对象的__proto__就是fNOP的实例fBound.prototype new fNOP();return fBound;};
} 转载于:https://www.cnblogs.com/YikaJ/p/10683142.html
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/918683.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!