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

Polyfill of 「new」 #50

Closed
PolluxLee opened this issue Jun 14, 2018 · 0 comments
Closed

Polyfill of 「new」 #50

PolluxLee opened this issue Jun 14, 2018 · 0 comments
Labels

Comments

@PolluxLee
Copy link
Owner

PolluxLee commented Jun 14, 2018

# new

形如,new Constructor(),new 然后紧接着一个构造函数可以创建一个新的对象,1)对象中包含构造函数中定义的实例属性,2)并且新对象的 __proto__ 指向构造函数的原型对象 prototype

// 构造函数
function func(name, age) {
  this.name = name;
  this.age = age;
}

func.prototype.showAge = function () {
  console.log(this.age);
}

// 测试一下
var obj = new func("April", 21);
console.log(obj.name);  //  April
obj.showAge();  //  21

# Polyfill

function objectFactory(func) {
  var obj = {};
  if (typeof func !== "function") return obj;
  var ret = func.apply(obj, [].slice.call(arguments, 1));

  // 考虑构造函数有返回值的情况
  // 当返回的是引用类型的时候,会覆盖 new 创建的对象
  if (typeof ret === "function" || typeof ret === "object") {
    return ret;
  }
  obj.__proto__ = func.prototype;
  return obj;
}

function func(name, age) {
  this.name = name;
  this.age = age;
}

func.prototype.showAge = function () {
  console.log(this.age);
}

# Test

// 测试一下
var obj = objectFactory(func, "April", 21);
console.log(obj.name);  //  April
obj.showAge();  //  21

# Reference

mqyqingfeng/Blog#13

@PolluxLee PolluxLee changed the title Polyfill of "new"(new 的模拟实现) Polyfill of "new" Jun 14, 2018
@PolluxLee PolluxLee changed the title Polyfill of "new" Polyfill of 「new」 Jun 14, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant