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中 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