一、使用 new 操作符调用构造函数实际上会经历以下 4个步骤:
(1) 创建一个新对象;
(2) 将构造函数的作用域赋给新对象(因此 this 就指向了这个新对象) ;
(3) 执行构造函数中的代码(为这个新对象添加属性) ;
(4) 返回新对象,如果该函数没有返回对象,则返回this。
function myNew(fn, ...arg) {
if (typeof fn !== 'function') {
throw new Error('myNew the first params must be a function')
}
//
let obj = Object.create(null)
// 将空对象指向构造函数的原型链
Object.setPrototypeOf(obj, Con.prototype);
let res = fn.call(obj, ...args)
return typeof res === 'object' || res instanceof Function ? res : obj;
}
二、原型链、constructor继承
'use strict'
const inherit = function (SuperConstructor, properties) {
let { constructor } = properties
let subConstructor = function(...args){
constructor.call(this, ...args)
SuperConstructor.call(this, ...args)
}
subConstructor.prototype = {
...properties,
constructor: subConstructor
}
Object.setPrototypeOf(
subConstructor.prototype,
SuperConstructor.prototype,
)
return subConstructor
}
const Human = inherit(Object, {
constructor( age ) {
this.age = age
},
showAge() {
console.log(this.age)
return this.age
}
})
const User = inherit(Human, {
constructor({ firstname, lastname }) {
this.firstname = firstname
this.lastname = lastname
},
showName() {
console.log('name', this.firstname + '' + this.lastname)
}
})
const user = new User({
age: 18,
firstname: 'Jade',
lastname: 'Gu'
})
console.log('User', User)