Implement a new

Dog function (name) {
this.name name =
this.say = function () {
the console.log ( 'name =' + this.name)
}
}
function Cat (name) {
this.name name =
this.say function = () {
the console.log ( 'name =' + this.name)
}
}
function _new (Fn, ... Arg) {
const obj = {}; // Create a new object
obj .__ proto__ = fn.prototype; // obj of the __proto__ point prototype fn, and implementation inheritance
fn.apply (obj, arg) // change this point of
return Object.prototype.toString.call (obj) == '[ object Object]'? obj : {} // return the new object obj
}

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

Guess you like

Origin www.cnblogs.com/MDGE/p/11563350.html