Samgao0312 / Blog

MIT License
1 stars 1 forks source link

【再学前端】JavaScript 中 new 一个对象实例的过程 #134

Open Samgao0312 opened 2 years ago

Samgao0312 commented 2 years ago

先看一段代码。

function Person(name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.sayName = function() {
  return "I'm " + this.name;
}

let gl = new Person('gdragon', 30);
console.log(gl.name)  //"gdragon"
console.log(gl.age)  //30
console.log(gl.sayName())  // "I'm gdragon"

从上面代码执行结果,我们可以得出下面两个结论:

进而我们可以得出下面结论。

new 一个对象的过程

实现我们自己的 new 函数

function Person (name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.sayName = function() {
  return "Hi, I am " + this.name;
}

function newMethod() {
  let obj = new Object();
  let Constructor = [].shift.call(arguments);
  obj.__proto__ = Constructor.prototype;
  let result = Constructor.apply(obj, arguments)
  return typeof result == 'object' ? result : obj;
}

let gl = newMethod(Person, 'G-Dragon', 30);
console.log(gl.name, gl.age)
console.log(gl.sayName())

几个属性方法

参考阅读