Loading

JS 手写之 new 运算符

new 运算符

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

语法

new constructor[[arguments]];

参数

  • constructor - 一个指定对象实例的类型的类或函数。
  • arguments - 一个用于被 constructor 调用的参数列表。

描述

new 关键字会进行如下的操作:

  • 创建一个空对象,将它的引用赋给 this,继承函数的原型。

  • 通过 this 将属性和方法添加至这个对象

  • 最后返回 this 指向的新对象,也就是实例(如果没有手动返回其他的对象)

myNew

/**
 * myNew
 * @param {Function} Parent
 * @param  {...any} args
 * @returns {Object}
 */
function myNew(Parent, ...args) {
  // 构造函数类型必须是方法
  if (typeof Parent !== "function") {
    throw new TypeError("first parameter is not a constructor");
  }
  // 创建一个继承自Parent.prototype的新对象
  var child = Object.create(Parent.prototype);
  // 将构造函数Parent的this绑定到child中
  Parent.apply(child, args);
  // 将创建的对象返回出去,就是 new 的结果
  return child;
}

测试

function Parent(name, age) {
  this.name = name;
  this.age = age;
}

Parent.prototype.sayName = function () {
  console.log(this.name);
};

var str = "";

// 失败测试
var a = myNew(str);
// first parameter is not a constructor

// 成功
var b = myNew(Parent, "frank", 18);
b.sayName(); // frank
b instanceof Parent; // true
b.hasOwnProperty("name"); // true
b.hasOwnProperty("age"); // true
b.hasOwnProperty("sayName"); // false
posted @ 2021-06-03 00:11  Frank-Link  阅读(141)  评论(0编辑  收藏  举报