欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

深入聊一聊JS中new的原理与实现

程序员文章站 2022-03-04 12:15:57
目录定义构造函数体不同无返回值返回对象返回非对象没有属性绑定+返回非对象构造函数类型不同构造函数为普通函数构造函数为箭头函数手写new总结定义new 运算符创建一个用户定义的对象类型的实例或具有构造函...

定义

new 运算符创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例。

使用new [constructor]的方式来创建一个对象实例,但构造函数的差异会导致创建的实例不同。

构造函数体不同

构造函数也是函数,其唯一的区别就是调用方式不同,任何函数只要使用 new 操作符调用就是构造函数,而不使用 new 操作符调用的函数就是普通函数。

因此构造函数也可以带有返回值,但是这会导致new的结果不同。

无返回值

function person(name) {
  this.name = name;
}

let obj = new person("jalenl");
console.log(obj);

显然,打印的是{name:'jalenl'}

返回对象

function person(age) {
  this.age = age;
  return { name: "jalenl" };
}

let obj = new person(18);
console.log(obj);

打印的是{name:'jalenl'},也就是说return之前的定义都被覆盖了。这里return的是一个对象,那返回的是个基本类型呢?

返回非对象

function person(age) {
  this.age = age;
  return 1;
}

let obj = new person(18);
console.log(obj);

返回{age:21},这么说return失效了,跟没有return一样的结果,那如果没有this绑定内部属性,再返回基本数据类型呢?

没有属性绑定+返回非对象

function person(){
    return 1
}
new person()

返回的是一个空对象{},意料之中。

综上,只有构造函数return返回的是一个对象类型时,才能改变初始结果。

构造函数类型不同

构造函数为普通函数

ecma-262 3rd. edition specification中的说明了对象实例的创建过程:

13.2.2 [[construct]]
when the [[construct]] property for a function object f is called, the following steps are taken:

  1. create a new native ecmascript object.
  2. set the [[class]] property of result(1) to "object".
  3. get the value of the prototype property of f.
  4. if result(3) is an object, set the [[prototype]] property of result(1) to result(3).
  5. if result(3) is not an object, set the [[prototype]] property of result(1) to the original object prototype object as described in 15.2.3.1.
  6. invoke the [[call]] property of f, providing result(1) as the this value and providing the argument list passed into [[construct]] as the argument values.
  7. if type(result(6)) is object then return result(6).
  8. return result(1).

总结下来就是:

  1. 在内存中创建一个新对象。
  2. 这个新对象内部的[[prototype]]特性被赋值为构造函数的 prototype 属性。
  3. 构造函数内部的 this 被赋值为这个新对象(即 this 指向新对象)。
  4. 执行构造函数内部的代码(给新对象添加属性)。
  5. 如果构造函数返回对象,则返回该对象;否则,返回刚创建的新对象(空对象)。

第五步就已经说明了构造函数不同导致new结果不同的原因。

以下摘自mdn的解释:

当代码 new foo(…) 执行时,会发生以下事情:

  1. 一个继承自 foo.prototype 的新对象被创建。
  2. 使用指定的参数调用构造函数 foo,并将 this 绑定到新创建的对象。new foo 等同于 new foo(),也就是没有指定参数列表,foo 不带任何参数调用的情况。
  3. 由构造函数返回的对象就是 new 表达式的结果。如果构造函数没有显式返回一个对象,则使用步骤1创建的对象。(一般情况下,构造函数不返回值,但是用户可以选择主动返回对象,来覆盖正常的对象创建步骤)

构造函数为箭头函数

普通函数创建时,引擎会按照特定的规则为这个函数创建一个prototype属性(指向原型对象)。默认情况下,所有原型对象自动获得一个名为 constructor 的属性,指回与之关联的构造函数。

function person(){
    this.age = 18;
}
person.prototype
/**
{
    constructor: ƒ foo()
    __proto__: object
}
**/

创建箭头函数时,引擎不会为其创建prototype属性,箭头函数没有constructor供new调用,因此使用new调用箭头函数会报错!

const person = ()=>{}
new person()//typeerror: foo is not a constructor

手写new

综上,熟悉了new的工作原理后,我们可以自己实现一个低配版的new,实现的关键是:

  1. 让实例可以访问到私有属性;
  2. 让实例可以访问构造函数原型(constructor.prototype)所在原型链上的属性;
  3. 构造函数返回的最后结果是引用数据类型。
function _new(constructor, ...args) {
    // 构造函数类型合法判断
    if(typeof constructor !== 'function') {
      throw new error('constructor must be a function');
    }
    // 新建空对象实例
    let obj = new object();
    // 将构造函数的原型绑定到新创的对象实例上
    obj.__proto__ = object.create(constructor.prototype);
    // 调用构造函数并判断返回值
    let res = constructor.apply(obj,  args);
    let isobject = typeof res === 'object' && res !== null;
    let isfunction = typeof res === 'function';
    // 如果有返回值且返回值是对象类型,那么就将它作为返回值,否则就返回之前新建的对象
    return isobject || isfunction ? res : obj;
};

这个低配版new实现可以用来创建自定义类的实例,但不支持内置对象,毕竟new属于操作符,底层实现更加复杂。

总结

到此这篇关于js中new的原理与实现的文章就介绍到这了,更多相关js中new原理与实现内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: js new 原理