[前端] JS手写bind之处理new的情况详解

1818 0
黑夜隐士 2022-10-21 15:11:08 | 显示全部楼层 |阅读模式
目录

    new判断函数是否通过 new 被调用new 和 bind实现完整的 bind结尾

大家好,我是前端西瓜哥。
之前写了一篇关于 JS 中 bind 方法的实现的文章,并给出了实现:
  1. Function.prototype.myBind = function(thisArg, ...prefixArgs) {
  2.   const fn = this;
  3.   return function(...args) {
  4.     return fn.call(thisArg, ...prefixArgs, ...args);
  5.   }
  6. }
复制代码
但没有处理 通过 new 创建实例 的情况。
因为很少会遇到给 bind 返回的函数做 new 操作的场景,所以我没去考虑这种特殊情况。
但面试中还是会涉及到的,我们还是实现一下兼容 new 操作的 bind 写法,顺便学习一下 new 操作符。
因为存在一定上下文,在阅读本文前,建议先阅读前一篇文章:《前端面试题:手写 bind》。

new

我们先学习一下 new 操作符。
new 用于通过函数来创建一个对象实例,在很多语言中都能看到。
JS 的函数,除了可以是普通函数,比如:
  1. function sum(a, b) {
  2.   return a + b;
  3. }
复制代码
还可以是构造函数,只需要在构造时在它前面加一个 new:
  1. function Person(name, age) {
  2. this.name = name;
  3. this.age = age;
  4. }
  5. const person = new Person('前端西瓜哥', 100)
  6. // Person {name: '前端西瓜哥', age: 100}
复制代码
new 创建一个新对象,做了下面几件事:
    创建一个空对象 {};空对象的原型属性 __proto__ 指向构造函数的原型对象 Person.prototype;函数中的 this 设置为这个空对象;如果该函数不返回一个对象,就返回这个 this,否则返回这个对象。

判断函数是否通过 new 被调用

怎么判断一个函数正在被 new 操作符调用?
答案是 使用 instanceof 判断 this 是否为当前函数的实例,即 this instanceof Fn 为 true,表示在通过 new 构建实例。
我们看一个例子:
  1. function Person() {
  2.   if (this instanceof Person) {
  3.     console.log('通过 new 构建实例');
  4.   } else {
  5.     console.log('普通调用')
  6.   }
  7. }
  8. Person()     // 输出:普通调用
  9. new Person() // 输出:通过 new 构建实例
复制代码
在 Vuejs 的源码,你会看到下面代码,这里也用到了这个技巧。
  1. function Vue(options) {
  2.   if (__DEV__ && !(this instanceof Vue)) {
  3.     warn('Vue is a constructor and should be called with the `new` keyword')
  4.   }
  5.   this._init(options)
  6. }
复制代码
你在开发环境如果不通过 new 来使用 Vue 对象,会在控制台提示你要通过 new 来调用 Vue。

new 和 bind

如果我们 new 的是 Function.prototype.bind 返回的新函数,会发生什么事情?
  1. function Person(name, age) {
  2. this.name = name;
  3. this.age = age;
  4. }
  5. const BoundPerson = Person.bind(null, '前端西瓜哥');
  6. const boundPerson = new BoundPerson(100);
  7. // Person {name: '前端西瓜哥', age: 100}
  8. boundPerson.__proto__ === Person.prototype
  9. // true
复制代码
结果等价于直接去 new 原始函数。
不同的是,仍旧可以进行参数的预置。可以看到,构造函数的第一个参数,在调用 bind 的时候就提前设置为 '前端西瓜哥'。

实现完整的 bind

完整实现如下:
  1. Function.prototype.myBind = function(thisArg, ...prefixArgs) {
  2.   const fn = this;
  3.   const boundFn = function(...args) {
  4.     // 通过 new 使用当前函数
  5.     if (this instanceof boundFn) {
  6.       return new fn(...prefixArgs, ...args);
  7.     }
  8.     // 普通的方法调用当前函数
  9.     return fn.call(thisArg, ...prefixArgs, ...args);
  10.   }
  11.   boundFn.prototype = fn.prototype;
  12.   return boundFn;
  13. }
复制代码
这里我通过 this instanceof boundFn 来判断是否用了 new,如果是,就直接 new 原始函数然后返回,记得带上 bind 预置好的参数。
其他保持原样(具体见上文《前端面试题:手写 bind》)。
boundFn.prototype = fn.prototype;  这个可写可不写,只是让 bind 返回的新函数的 prototype 指向原函数的 prototype。
如果是原生 bind 返回的函数,它是没有 protoype 属性的,可以认为它是一种特别的函数,而我们实现的 bind 返回的却是一个普通函数,所以并不能完全模拟的。
如果你 追求完美的实现,可以研读一下  Function.prototype.bind 的标准:
然后再看看知名的 core.js 库中对 bind 的实现:
其中核心实现为:
  1. // `Function.prototype.bind` method implementation
  2. // https://tc39.es/ecma262/#sec-function.prototype.bind
  3. module.exports = Function.bind || function bind(that /* , ...args */) {
  4.   var F = aCallable(this);
  5.   var Prototype = F.prototype;
  6.   var partArgs = arraySlice(arguments, 1);
  7.   var boundFunction = function bound(/* args... */) {
  8.     var args = concat(partArgs, arraySlice(arguments));
  9.     return this instanceof boundFunction ? construct(F, args.length, args) : F.apply(that, args);
  10.   };
  11.   if (isObject(Prototype)) boundFunction.prototype = Prototype;
  12.   return boundFunction;
  13. };
复制代码
这里有更多的细节:
    这里判断了 this 是否为函数类型,不是函数会报错;F.prototype 需要是一个对象或函数,才能赋值给新函数;使用了普通函数和 arguments,这是为了兼容 ES5。

结尾

手写 bind,现在想来并不简单,需要掌握好很多知识点:
    bind 的详尽用法:包括改变 this、预置参数、new 的表现;闭包的使用:保存一些私有变量;通过原型链的方式(this instanceof boundFn)判断是否通过 new 调用当前函数;使用 call 在执行时改变函数的 this 指向。
到此这篇关于JS手写bind之处理new的情况详解的文章就介绍到这了,更多相关JS处理new内容请搜索中国红客联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持中国红客联盟!
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行