bind
by Alex Liu
JavaScript
Function.prototype.bind2 = function(context) {
const slice = Array.prototype.slice
const args = slice.call(arguments, 1)
const self = this
const Anon = function() {}
Anon.prototype = self.prototype
const ret = function() {
const args2 = args.concat(slice.call(arguments))
return self.apply(this instanceof Anon ? this : context || {}, args2)
}
ret.prototype = new Anon()
return ret
}
function Animal(name, color) {
this.name = name
this.color = color
}
Animal.prototype.say = function() {
return `${this.name}: ${this.color}`
}
const Cat = Animal.bind2(null, 'cat')
const cat = new Cat('white')
if (cat.say() === 'cat: white' && cat instanceof Cat && cat instanceof Animal) {
console.log('success')
}