定义
-
构造函数:通过
new操作符调用,运行后会返回一个对象,该对象的__proto__属性指向构造函数.prototype -
当构造函数本身会返回一个非null的对象时,则通过
new会返回这个对象,其他情况还是会返回新生成的对象
function Cat(name) {
this.name = name
}
Cat.prototype.miao = function() {
console.log('喵~!');
}
let cat = new Cat('大毛')
console.log(cat.__proto__ === Cat.prototype); //true
new 执行全过程
-
创建一个对象 -
构造函数作用域赋给新对象 -
构造函数中的 this 指向该对象 -
返回一个新的对象
new 一个箭头函数会发生什么呢? **
- 箭头函数 没有 prototype,也没有独立的 this 指向,更没有 arguments
实现 new
-
用函数来模拟
new的功能- 由于
new是语言层面的操作符
- 由于
function newFactory() {
let constructor = arguments[0]
let obj = Object.create(constructor.prototype)
constructor.apply(obj, Array.from(arguments).slice(1));
return obj
}
function Cat(name) {
this.name = name
}
Cat.prototype.miao = function() {
console.log('喵~!');
}
let cat = newFactory(Cat,'大毛')
- 改进:当构造函数本身会返回一个非null的对象时,则通过
new会返回这个对象,其他情况还是会返回新生成的对象
function Cat(name) {
this.name = name
return {
name:'zs'
}
}
Cat.prototype.miao = function() {
console.log('喵~!');
}
let cat = new Cat('大毛')
console.log(cat.name) //'zs'
- 因此需要将调用
Cat后返回的结果进行判断,如果是非null的对象,则返回该对象,其他情况返回新生成的对象
function newFactory() {
let constructor = arguments[0]
let obj = Object.create(constructor.prototype)
let result = constructor.apply(obj, Array.from(arguments).slice(1));
return result instanceof Object ? result : obj
}
function Cat(name) {
this.name = name
return {
name:'zs'
}
}
Cat.prototype.miao = function() {
console.log('喵~!');
}
let cat = new Cat('大毛')