javascript 基础之 call, apply, bind

系统,扎实的 javascript 语言基础是一个优秀的前端工程师必须具备的。在看了一些关于 call,apply,bind 的文章后,我还是打算写下这篇总结,原因有几个。首先,在如今 ES6 大行其道的今天,很多文章中讲述的它们的应用场景其实用 ES6 可以更优雅的解决,但是基本上没有文章会去提 ES6 的解法。再则,讲它们的实现原理的文章其实不少,但是或多或少实现的有些不够完美,本文将把它们通过代码一一比较完美的实现,让它们不再神秘。不谦虚的说,关于 call,apply,bind 的知识,看这一篇文章就够了。

改变函数中 this 指向的三兄弟

我们知道在 javascript 的 function 中有 thisarguments 等关键字。本文不讨论 this 指向问题,那个都可以单独整一篇文章了。一个常见的使用场景是当你使用 . 来调用一个函数的时候,此时函数中 this 指向 . 前面的调用者:

const person = {
 name: 'YuTengjing',
 age: 22, 
 introduce() {
 console.log(`Hello everyone! My name is ${this.name}. I'm ${this.age} years 
 old.`); 
} 
}; ​ // this 此时指向 person console.log(person.introduce()); // => Hello everyone! My name is YuTengjing. I'm 22 years old. 

通过 call,apply,bind 这三兄弟可以改变 introduce 中 this 的指向。

call

const myFriend = {
    name: 'dongdong',
    age: 21,
};
​
console.log(person.introduce.call(myFriend)); // => Hello everyone! My name is dongdong. I'm 21 years old.

通过上面代码我们可以看出 introduce 这个函数中的 this 指向被改成了 myFriend。Function.prototype.call 的函数签名是 fun.call(thisArg, arg1, arg2, ...)。第一个参数为调用函数时 this 的指向,随后的参数则作为函数的参数并调用,也就是 fn(arg1, arg2, ...)。

apply

apply 和 call 的区别只有一个,就是它只有两个参数,而且第二个参数为调用函数时的参数构成的数组。函数签名:func.apply(thisArg, [argsArray])。如果不用给函数传参数,那么他俩就其实是完全一样的,需要传参数的时候注意它的应该将参数转换成数组形式。

一个简单的例子:

function displayHobbies(...hobbies) {
    console.log(`${this.name} likes ${hobbies.join(', ')}.`);
}
​
// 下面两个等价
displayHobbies.call({ name: 'Bob' }, 'swimming', 'basketball', 'anime'); // => // => Bob likes swimming, basketball, anime. 
displayHobbies.apply({ name: 'Bob' }, ['swimming', 'basketball', 'anime']); // => Bob likes swimming, basketball, anime.

bind

bind 和上面两个用途差别还是比较大,如同字面意思(绑定),是用来绑定 this 指向的,返回一个原函数被绑定 this 后的新函数。一个简单的例子:


const person = {
    name: 'YuTengjing',
    age: 22,
};
​
function introduce() {
    console.log(`Hello everyone! My name is ${this.name}. I'm ${this.age} years old.`);
}
​
const myFriend = { name: 'dongdong', age: 21 };
person.introduce = introduce.bind(myFriend);
​
// person.introduce 的 this 已经被绑定到 myFriend 上了
console.log(person.introduce()); // => Hello everyone! My name is dongdong. I'm 21 years old.
console.log(person.introduce.call(person)); // => Hello everyone! My name is dongdong. I'm 21 years old.

bind 的函数签名是 func.bind(thisArg, arg1, arg2, ...)

学以致用

我们学习知识的时候不能只是停留在理解层面,需要去思考它们有什么用,应用场景有哪些。这样的话,当你处在这种场景中,你就能很自然的想出解决方案。

多参函数转换为单个数组参数调用

javascript 中有很多 API 是接受多个参数的比如之前提过的 Math.max,还有很多例如 Math.min,Array.prototype.push 等它们都是接受多个参数的 API,但是有时候我们只有多个参数构成的数组,而且可能还特别大,这个时候就可以利用 apply 巧妙的来转换。

下面是利用 apply 来巧妙的合并数组:

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
​
Array.prototype.push.apply(arr1, arr2);
console.log(arr1); // [1, 2, 3, 4, 5, 6]

但是,其实用 ES6 可以非常的简洁:

arr1.push(...arr2)

所以这个用法就是“可以,但没必要”

将类数组转换为数组

JavaScript类型化数组是一种类似数组的对象,它们有数组的一些属性,但是如果你用 Array.isArray() 去测试会返回 false,常见的像 arguments,NodeList 等。

function testArrayLike() {
    // 有 length 属性没有 slice 属性
    console.log(arguments.length); // => 3
    console.log(arguments.slice); // => undefined
​
    // 类数组不是数组
    console.log(Array.isArray(arguments)); // => false
    console.log(arguments); // => { [Iterator]  0: 'a', 1: 'b', 2: 'c', [Symbol(Symbol.iterator)]: [λ: values] } 
    
    const array = Array.prototype.slice.call(arguments);
    console.log(Array.isArray(array)); // => true
    console.log(array); // => [ 'a', 'b', 'c' ]
}
​
testArrayLike('a', 'b', 'c');

其实 把 slice 换成 concat,splice 等其它 API 也是可以的。思考:为什么通过 Array.prototype.slice.call(arrayLike) 可以转换类数组为数组?

我没有研究过 slice 的具体实现,猜测是下面这样的:

Array.prototype.mySlice = function(start=0, end) {
    const array = this;
    const end = end === undefined ? array.length : end;
    
    const resultArray = [];
    if (array.length === 0) return resultArray;
    for (let index = start; index < end; index++) {
        resultArray.push(array[index]);
    }
    return resultArray;
}

我想 slice 内部实现可能就是会像我上面的代码一样只需要一个 length 属性,遍历元素返回新数组,所以调用 slice 时将其 this 指向类数组能正常工作。

其实,这个用法也可以忘了,用 ES6 来转换不造多简单,ES6 大法好 。

可以使用 Array.from(arrayLike):

const array = Array.from(arguments);

还可以使用扩展运算符:

const array = [...arguments];

组合继承

ES6 class 出现之前,个人认为比较完美的继承是使用原型链加组合的继承方式。这里不展开讲 javascript 的继承,那会又是一个巨坑。

组合继承其实很好理解,这个组合指的是子类的实例属性组合了父类的实例属性,看代码

function Animal(type) {
    this.type = type;
}
​
function Bird(type, color) {
    Animal.call(this, type);
    this.color = color;
}
​
const bird = new Bird('bird', 'green');
console.log(bird); // => Bird { type: 'bird', color: 'green' }

组合继承核心代码就是那句 Animal.call(this, type),通过调用父类构造器并修改其 this 指向为子类实例来达到子类实例上组合父类的实例属性目的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值