call、apply、bind的作用与应用
apply
介绍
- apply()方法接收两个参数:一个是在其中运行函数的作用域,另一个是参数数组。
例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| function sum(num1, num2){ return num1 + num2; }
function callSum1(num1, num2){ return sum.apply(this, arguments); }
function callSum2(num1, num2){ return sum.apply(this, [num1, num2]); }
alert(callSum1(10,10)); alert(callSum2(10, 10));
(1) 不传,或者传null,undefined, 函数中的this指向window对象 (2) 传递另一个函数的函数名,函数中的this指向这个函数的引用 (3) 传递字符串、数值或布尔类型等基础类型,函数中的this指向其对应的包装对象,如 String、Number、Boolean (4) 传递一个对象,函数中的this指向这个对象
|
call
介绍
- call()方法接收多个参数:第一个是在其中运行函数的作用域,其他都是参数都直接传递给函数。
例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| window.color = "red"; var o = { color: "blue" };
function sayColor(){ alert(this.color); }
sayColor();
sayColor.call(this); sayColor.call(window);
sayColor.call(o);
|
[].slice.call(arguments) 等价于 Array.prototype.slice.call(arguments)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| const likeArr = { 0: "test", 1: "测试", length: 2 }
[].slice.call(likeArr);
var args = []; for (var i = 0; i < likeArr.length; i++) { args.push(likeArr[i]); } console.log(args);
console.log([1,2,3].slice(0,1)) console.log([1,2,3].slice())
function func(name, price) { this.name = name; this.price = price; } var food = {name:"apple",price:10}; func.call(food,"orange",15); console.log(food);
[].slice.call(arguments) --> Array.prototype.slice.call(arguments)
|
Array.prototype.map.call()
作用:让类数组对象(如 arguments、NodeList)使用 map() 方法。
1 2 3 4 5 6
| function example() { const doubled = Array.prototype.map.call(arguments, (num) => num * 2); console.log(doubled); }
example(1, 2, 3);
|
Object.prototype.toString.call()
作用:准确判断数据类型,比 typeof 更可靠
运行机制:
每个 JavaScript 内置对象(如 Array、Function、Date 等)都有一个内部的 [[Class]] 属性,该属性通过 Object.prototype.toString.call(value) 返回 [object Type] 格式的字符串。
1 2 3 4 5 6
| console.log(Object.prototype.toString.call([])); console.log(Object.prototype.toString.call({})); console.log(Object.prototype.toString.call(null)); console.log(Object.prototype.toString.call(undefined)); console.log(Object.prototype.toString.call(/\d/)); console.log(Object.prototype.toString.call(new Date()));
|
bind
介绍
- 这个方法会创建一个函数的实例,其this值会被绑定到传给bind()函数的值。 便于后期调用, 不同于call、apply立即调用。
例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| var bar=function(){ console.log(this.x); } var foo={ x:3 } bar(); bar.bind(foo)(); var func=bar.bind(foo); func();
输出: undefined 3
|