call,apply,bind三者的区别
作者:互联网
//call,apply,bind三者的区别
let Dog = {
name: '狗狗',
eat(op1, op2) {
console.log(this.name + '吃' + op1 + op2)
}
}
let Cat = {
name: '喵喵'
}
Dog.eat.call(Cat, '鱼', '肉')//通过Call让Cat去调用Dog.eat方法,参数 用逗号隔开
Dog.eat.apply(Cat, ['鱼', '肉'])//与call方法的区别是参数需要用数组包起来
let Cat_eat = Dog.eat.bind(Cat, '鱼', '肉')//参数的传递方法和call一致,但是不会执行eat方法,而是返回一个可执行函数。
Cat_eat()
//利用call方法实现继承(包含多重继承) function Animal() { this.move = function () { console.log('行动') } } function Brid() { this.fly = function () { console.log('飞行') } } People.prototype = new Animal()//通过原型链实现继承 function People() { Animal.call(this) Brid.call(this)//通过call方法实现多重继承 } let people = new People() people.move() people.fly()
//利用call方法实现继承(包含多重继承) function Animal() { this.move = function () { console.log('行动') } } function Brid() { this.fly = function () { console.log('飞行') } } People.prototype = new Animal()//通过原型链实现继承 function People() { Animal.call(this) Brid.call(this)//通过call方法实现多重继承 } let people = new People() people.move() people.fly()
标签:function,let,bind,Dog,Cat,call,apply,eat 来源: https://www.cnblogs.com/GFM0518/p/16582779.html