直接上干货
展示new操作符的效果
function Shape (x) {
this.x = x
this.draw = function () {}
}
// 定义公共方法
Shape.prototype.commonDraw = function () {}
const circle = new Shape(3)
console.dir(circle)
如图展示是使用new操作符的效果
解释:new操作符理解为copy了Shape,并且circle的this的指向变为了自己,circle的__proto__指向了Shape.prototype。 按照上述思路,不使用new操作符的实现方法如下:首先改变Shape的内部this指向,再把circle的__proto__指向Shape.prototype
上代码
function createNew () {
let constructor = Array.prototype.shift.call(arguments) // 获取到参数列表的第一个值,为需要被new的函数
if (typeof constructor !== 'function') { // 判断参数不为Function,则报错
throw 'constructor error'
}
let sub = {} // 构建一个空对象
constructor.call(sub, ...arguments) // 执行constructor,传入参数,并改变this指向为sub
sub.__proto__ = constructor.prototype // 改变sub的__proto__指向
return sub
}
const sub = createNew(Shape, 3)
console.dir(sub)
结果如图展示,与new出来的函数一模一样,但是并不相等。
或者使用Object.create方法
function createNew () {
let constructor = Array.prototype.shift.call(arguments)
if (typeof constructor !== 'function') {
throw 'constructor error'
}
let sub = Object.create(constructor.prototype);
constructor.call(sub, ...arguments)
return sub
}
效果一样。