You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
functionPerson(name){this.name=name;}Person.prototype.getName=function(){returnthis.name;}varp1=newPerson('Dan');console.log(p1);// Person {name: "Dan"}console.log(p1.__proto__===Person.prototype);// true
new 操作符实现了如下的功能:
创建一个新对象
新对象的原型指向构造函数的原型对象性,即继承构造函数的原型
改变构造函数 this 的指向到新建的对象,并执行构造函数
判断返回的值是不是一个对象,若是则返回这个对象,否则返回新对象
构造函数如果返回基本类型,则还是会返回原来的 this (新对象)。如果返回的是引用类型,则返回该返回值。(可以自己在上面例子加上代码验证一下)
new 操作符的模拟实现
functioncreateNew(func, ...args){letobj={};// 将空对象指向构造函数的原型链Object.setPrototypeOf(obj,func.prototype);// obj 绑定到构造函数上,便可以访问构造函数中的属性letresult=func.apply(obj,args);// 如果返回的 result 是一个对象则返回该对象,new 方法失效,否则返回 objreturnresultinstanceofObject ? result : obj;}
实例代码:
new 操作符实现了如下的功能:
构造函数如果返回基本类型,则还是会返回原来的 this (新对象)。如果返回的是引用类型,则返回该返回值。(可以自己在上面例子加上代码验证一下)
new 操作符的模拟实现
写个测试用例:
The text was updated successfully, but these errors were encountered: