call、apply、bind
概述:call、apply、bind都改变了this的指向,具体改变this指向要做什么。举个简单的例子。
let fn = function (a, b) {
console.log(this, a, b);
console.log(this.name, a, b);
}
let obj = {
name: "obj"
};
//三种用法
fn.call(obj, 1, 2);
fn.apply(obj, [1, 2]);
let fn1 = fn.bind(obj); fn1(1, 2)
函数fn中this原本指向的是window。现通过call方法将this指向了obj。那么就可以在fn函数中,通过this.name拿到obj对象中的name进行使用了。
call、apply、bind都是函数的方法
总结:函数fn要使用obj中的属性值时使用到call,apply,bind
用处
继承:子类可以使用父类的方法
call的好处:可以实现多重继承
function Animal() {
// 这个this指向的也是cat
this.eat = function () {
console.log("吃东西");
}
}
function Bird() {
this.fly = function () {
console.log("飞翔");
}
}
let animal = new Animal()
animal.eat() //吃东西
function Cat() {
// 这个this指向的是cat
Animal.call(this)
Bird.call(this)
}
let cat = new Cat()
cat.eat() //吃东西
cat.fly() //飞翔