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
functionmyNew(constructor, ...args){// 创建一个新对象,该对象继承自构造函数的原型constobj=Object.create(constructor.prototype);// 调用构造函数,并将新对象作为this值传递进去constresult=constructor.apply(obj,args);// 如果构造函数返回一个对象,则返回该对象,否则返回新创建的对象returntypeofresult==='object'&&result!==null ? result : obj;}
使用示例:
functionPerson(name,age){this.name=name;this.age=age;}Person.prototype.sayHello=function(){console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);}constjohn=myNew(Person,"John",25);john.sayHello();// 输出:Hello, my name is John and I'm 25 years old.
关键词:模拟 new
可以使用以下代码来模拟
new
操作:使用示例:
在上述代码中,
myNew
函数模拟了new
操作的过程:Object.create
创建了一个新对象obj
,并将构造函数的原型对象赋值给该新对象的原型。apply
方法调用构造函数,并传入新对象obj
作为this
值,以及其他参数。obj
。这样,我们就可以使用
myNew
函数来模拟new
操作了。The text was updated successfully, but these errors were encountered: