如何手写call、apply、bind?

callFunction.prototype.call(this, arg1, arg2, …..)可以改变this,并且传入参数,立刻执行,返回函数返回值手写callFunction.prototype.myCall = function(context = window, …args) { context = context || window; // 参数默认值并不会排除null,所以重新赋值 context.fn = this; // this是调用call的函数 const result = context.fn(…args); delete context.fn; // 执行后删除新增属性 return result;}applyFunction.prototype.apply(this, [arg1, arg2, …..])可以改变this,并且传入参数,与call不同的是,传入的参数是数组或类数组,立刻执行,返回函数返回值手写apply:Function.prototype.myApply = function(context = window, args = []) { context = context || window; // 参数默认值并不会排除null,所以重新赋值 context.fn = this; // this是调用call的函数 const result = context.fn(…args); delete context.fn; return result;}bindFunction.prototype.bind(this, arg1, arg2, …)可以绑定this,并且传入参数,方式与call相同,但是不会执行,返回已绑定this的新函数手写bind:Function.prototype.myBind = function(context, …args) { const _this = this; return function Bind(…newArgs) { // 考虑是否此函数被继承 if (this instanceof Bind) { return _this.myApply(this, […args, …newArgs]) } return _this.myApply(context, […args, …newArgs]) }} ...

April 11, 2019 · 1 min · jiezi

重写JS中的apply,call,bind,new方法

在js中,经常会用到apply,call, bind, new,这几个方法在前端占据非常重要的作用,今天来看一下这些方法是如何实现,方便更加深入的理解它们的运作原理。this的绑定问题引用一点点其他知识点:一个方法的内部上下文this如何确定?一个方法的调用分为一下四种:方法直接调用,称之为函数调用,当前的上下文this,绑定在全局的window上,在严格模式use strict下,this为null方法作为一个对象的属性,这个是否通过对象调用方法,this绑定在当前对象上。如下:let dog = { name: ‘八公’, sayName: function() { console.log(this.name) }}dog.sayName() // 八公apply,call调用模式,当前的方法的上下文为方法调用的一个入参,如下:function sayHello() { console.log(this.hello)}let chineseMan = { hello: ‘你好啊’}sayHello.apply(chineseMan) // 你好啊let englishMan = { hello: ‘how are you’}sayHello.apply(englishMan) // how are you构造函数的调用,当前方法的上下文为新生的实例,如下// 声明构造函数function Animal(name) { this.name = name this.sayName = function() { console.log(this.name) }}let dog = new Animal(‘dog’)dog.sayName() // doglet cat = new Animal(‘cat’)cat.sayName() // cat正文apply实现思路:apply方法实现在Function.prototype中获取到当前调用方法体获取方法的入参绑定方法体中的上下文为传入的context–使用的方法就是对象调用属性方法的方式绑定调用方法Function.prototype.myApply = function() {let _fn = thisif (typeof _fn !== ‘function’) { throw new TypeError(’error’)}let ctx = […arguments].shift()// 因为apply的入参是数组,所有只需要取第一个let args = […arguments].slice(1).shift()ctx.myApplyFn = _fn// 由于apply会将原方法的参数用数组包裹一下,所以需要展开参数let res = ctx.myApplyFn(…args)delete ctx.myApplyFnreturn res}call实现思路:实现在Function.prototype中,大致和apply相似,却别在对于参数的处理上获取到当前调用方法体获取方法的入参绑定方法体中的上下文为传入的context调用方法Function.prototype.myCall = function() {let _fn = thisif (typeof _fn !== ‘function’) { throw new TypeError(’error’)}let ctx = […arguments].shift()// call使用的多个入参的方式,所有直接取参数第二个参数开始的所有入参,包装成一个数组let args = […arguments].slice(1)ctx.myCallFn = _fnlet res = ctx.myCallFn(…args) delete ctx.myCallFn return res}bind实现思路:实现在Function.prototype中,并且返回一个已经绑定了上下文的函数。利用闭包可以捕获函数上下文的变量来实现,总体上比起之前两个方法稍微复杂一些。获取调用bind的实例方法体获取需要绑定的上下文context声明闭包函数闭包函数中绑定context到实例方法体中闭包函数中调用原来的方法体返回闭包函数Function.prototype.myBind = function() { let _fn = this if (typeof _fn !== ‘function’) { throw new TypeError(’error’) } let ctx = […arguments].shift() let args = […arguments].slice(1) return function() { // 因为bind的调用方式,会有bind({}, ‘para1’, ‘para2’)(‘para3’, ‘para4’),这个时候需要将外面参数和内部参数拼接起来,之后调用原来方法 args = args.concat([…arguments]) ctx.myBindFn = _fn let res = ctx.myBindFn(…args) delete ctx.myBindFn return res }}codepen演示 需要翻墙<p class=“codepen” data-height=“265” data-theme-id=“0” data-default-tab=“js,result” data-user=“beyondverage0908” data-slug-hash=“PXMyqB” style=“height: 265px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid black; margin: 1em 0; padding: 1em;” data-pen-title=“rewrite bind”> <span>See the Pen rewrite bind by avg (@beyondverage0908) on CodePen.</span></p><script async src=“https://static.codepen.io/ass...;></script>new 方法实现思路:需要明白new到底做了什么生成一个新的实例对象实例对象__proto__链接到构造函数的prototype对象绑定构造函数的上下文为当前实例获取参数,传入参数,并调用构造函数function newObj() {let _o = {}let constructor = […arguments].shift()let args = […arguments].slice(1)if (typeof constructor !== ‘function’) { throw new TypeError(’error’)}_o.proto = constructor.prototype// 第一种调用方式:借助apply,call,或者bind实现绑定_o// constructor.apply(_o, args)// 第二种,使用属性方法绑定的方式_o.myNewFn = constructor_o.myNewFn(…args)delete _o.myNewFnreturn _o}// how to use - 如何使用function Animal(name, weight) {this.name = namethis.weight = weight}let dog = newObj(Animal, ‘dog’, ‘18kg’)// the animal name: dog weight: 18kgconsole.log(the animal name: ${dog.name} weight: ${dog.weight})let cat = newObj(Animal, ‘cat’, ‘11kg’)// the animal name: cat weight: 11kgconsole.log(the animal name: ${cat.name} weight: ${cat.weight})codepen需要翻墙<p class=“codepen” data-height=“265” data-theme-id=“0” data-default-tab=“js,result” data-user=“beyondverage0908” data-slug-hash=“MZNPoK” style=“height: 265px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid black; margin: 1em 0; padding: 1em;” data-pen-title=“MZNPoK”> <span>See the Pen MZNPoK by avg (@beyondverage0908) on CodePen.</span></p><script async src=“https://static.codepen.io/ass...;></script>结语熟悉函数内部的实现,了解内部的原理,对理解运行会有很多好处,亲自实现一遍会给你很多领悟。同时这些知识点又是非常重要的。 ...

January 22, 2019 · 2 min · jiezi