Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

模拟new操作【热度: 1,186】 #479

Open
yanlele opened this issue Jul 18, 2023 · 0 comments
Open

模拟new操作【热度: 1,186】 #479

yanlele opened this issue Jul 18, 2023 · 0 comments
Labels
JavaScript JavaScript 语法部分 滴滴 公司标签
Milestone

Comments

@yanlele
Copy link
Member

yanlele commented Jul 18, 2023

关键词:模拟 new

可以使用以下代码来模拟new操作:

function myNew(constructor, ...args) {
    // 创建一个新对象,该对象继承自构造函数的原型
    const obj = Object.create(constructor.prototype);
    
    // 调用构造函数,并将新对象作为this值传递进去
    const result = constructor.apply(obj, args);
    
    // 如果构造函数返回一个对象,则返回该对象,否则返回新创建的对象
    return typeof result === 'object' && result !== null ? result : obj;
}

使用示例:

function Person(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.`);
}

const john = myNew(Person, "John", 25);
john.sayHello(); // 输出:Hello, my name is John and I'm 25 years old.

在上述代码中,myNew函数模拟了new操作的过程:

  1. 首先,通过Object.create创建了一个新对象obj,并将构造函数的原型对象赋值给该新对象的原型。
  2. 然后,使用apply方法调用构造函数,并传入新对象obj作为this值,以及其他参数。
  3. 最后,根据构造函数的返回值判断,如果返回的是一个非空对象,则返回该对象;否则,返回新创建的对象obj

这样,我们就可以使用myNew函数来模拟new操作了。

@yanlele yanlele added JavaScript JavaScript 语法部分 滴滴 公司标签 labels Jul 18, 2023
@yanlele yanlele added this to the milestone Jul 18, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript JavaScript 语法部分 滴滴 公司标签
Projects
None yet
Development

No branches or pull requests

1 participant