使用 new 来调用函数,或者说发生构造函数调用时,会自动执行下面的操作。
- 创建(或者说构造)一个全新的对象。
- 这个新对象会被执行 [[ 原型 ]] 连接。
- 这个新对象会绑定到函数调用的 this。
- 如果函数没有返回其他对象,那么 new 表达式中的函数调用会自动返回这个新对象。
function Person(name) {
this.name = name
}
Person.prototype.getName = function () {
return this.name
}
function objectCreate(...params) {
let obj = new Object()
let Constructor = {}
Constructor = Array.prototype.shift.call(arguments)
obj.__proto__ = Constructor.prototype
var ret = Constructor.apply(obj, arguments);
return typeof ret === 'object' ? ret : obj;
}
let obj = objectCreate(Person,'helloworld')
console.log(obj instanceof Person) // true
console.log(Person.prototype.isPrototypeOf(obj)) // true
let per = new Person('helloworld')
console.log(per)