JS 手写之 new 运算符

时间:2021-06-03 17:49:20   收藏:0   阅读:0

new 运算符

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

语法

new constructor[[arguments]];

参数

描述

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

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中
  var res = Parent.apply(child, args);
  // 一般情况下,构造函数不返回值,我们选择主动返回对象,来覆盖正常的对象创建步骤
  return typeof res === "object" ? res : 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
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!