blog icon indicating copy to clipboard operation
blog copied to clipboard

new操作符做了什么

Open LiuL0703 opened this issue 7 years ago • 0 comments

new操作符创建对象可以分为四个步骤:

1 . 创建一个空对象 2 . 将所创建对象的__proto__属性值设成构造函数的prototype属性值 3 . 执行构造函数中的代码,构造函数中的this指向该对象 4 . 返回该对象(除非构造函数中返回一个对象)

function Person(a, b) {
  this.name = a;
  this.age = b;
}

Person.prototype.show = function() {
  console.log(this.name, this.age);
};

var p = new Person('cat', 1);
console.log(p);  //  Person {name: "cat", age: 1}

function Person(a, b) {
  this.name = a;
  this.age = b;
}

Person.prototype.show = function() {
  console.log(this.name, this.age);
};

// var p = new Person('cat', 1);
var p = {};
p.__proto__ = Person.prototype;
Person.call(p, 'cat', 1);

console.log(p);  //  Person {name: "cat", age: 1}    与上段代码输出表现一致

function fakeNew() {
  const obj = Object.create(null)
  const C = [].shift.call(arguments)
  obj.__proto__ = C.prototype
  const ret = C.apply(obj, arguments)
  return typeof ret === 'object' && ret !== null ? ret : obj
}

LiuL0703 avatar Jan 03 '18 05:01 LiuL0703