构造函数与 new 命令
构造函数
传统的面向对象语言中,Class是对象的模板,在 JS 中,面向对象基于构造函数和原型链实现,构造函数就是对象的模板。
构造函数有两个特点:
- new 命令
- 内部使用 this 关键字
new
new 命令就是执行构造函数,返回实例对象。当使用 new 命令时,会发生下面的流程:
- 创建一个空对象
o,作为将要返回的对象实例 - 将这个
o的原型指向构造函数的prototype属性 - 将这个
o赋值给函数内部的this - 执行内部构造函数代码
- 如果构造函数有显式的
return一个对象,则返回之,否则返回this对象
js
// new 命令的执行流程伪代码
function _new(_constructor, _param1, _param2){
const args = Array.prototype.slice(arguments) // 获取所有参数
const constructor = args.shift() // 构造函数
const context = Object.create(constructor.prototype) // 基于原型创造对象
const result = constructor.apply(context, args)
// 如果构造函数显式返回一个对象,则返回之
if(typeof result === 'object' && result != null) {
return result
}
// 否则返回context对象
return context
}