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关键字 #492

Open
YMnotafraid opened this issue Mar 20, 2023 · 1 comment
Open

手写new关键字 #492

YMnotafraid opened this issue Mar 20, 2023 · 1 comment

Comments

@YMnotafraid
Copy link

No description provided.

@YMnotafraid
Copy link
Author

function mynew(fn, ...args) {
  //实例对象的原型指向构造函数的原型对象
  const obj = Object.create(fn.prototype);
  //构造函数中this指向当前实例实例对象
  const res = fn.apply(obj, args);
  //判断构造函数的返回类型,普通类型则返回obj,引用类型则返回res
  return res instanceof Object ? res : obj;
}

function Fn(a, b) {
  this.name = a;
  this.age = b;
}
Fn.prototype = {
  getAge: function () {
    return this.age;
  },
  getName: function () {
    return this.name;
  },
};

const fn = mynew(Fn, "lbw", 18);
console.log(fn.getAge(), fn.getName());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant