实现一个new

function Dog(name) {
this.name = name
this.say = function () {
console.log('name = ' + this.name)
}
}
function Cat(name) {
this.name = name
this.say = function () {
console.log('name = ' + this.name)
}
}
function _new(fn, ...arg) {
const obj = {}; //创建一个新的对象
obj.__proto__ = fn.prototype; //把obj的__proto__指向fn的prototype,实现继承
fn.apply(obj, arg) //改变this的指向
return Object.prototype.toString.call(obj) == '[object Object]'? obj : {} //返回新的对象obj
}

//测试1
var dog = _new(Dog,'aaa')
dog.say() //'name = aaa'
console.log(dog instanceof Dog) //true
console.log(dog instanceof Cat) //false
//测试2
var cat = _new(Cat, 'bbb');
cat.say() //'name = bbb'
console.log(cat instanceof Cat)

转载于:https://www.cnblogs.com/MDGE/p/11563350.html

你可能感兴趣的:(实现一个new)