【JavaScript 学习--09】--理解Js 中的apply, call和bind方法

定义

  • call方法:
    语法function.call(thisArg, arg1, arg2, ...)
    定义:call()调用一个function,而这个function的this替换为给定的thisArg对象,并且函数参数可以一个一个的单独提供(The call() method calls a function with a given this value and arguments provided individually.)。
    说明:call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisArg指定的新对象。
    如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。

  • apply方法:
    语法function.apply(thisArg, [argsArray])
    定义:apply()调用一个function,而这个function的this替换为给定的thisArg对象, 并且函数参数必须是数组形式。(The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object).)。
    说明: 如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。
    如果没有提供 argArray 和 thisArg 任何一个参数,那么 Global 对象将被用作 thisArg, 并且无法被传递任何参数

apply和call区别:

apply()和call()方法的作用一样,都是在特定的作用域中调用函数, 。区别在于接受参数的方式不同。
call和apply可以改变函数作用域,将this指针指向改方法的第一个参数。

好处

这两个方法可以扩充作用域,使得对象不需要与方法之间有任何耦合关系了。

扩展:其实还有bind()方法,用来创建一个函数的实例,其this值会被绑定到给定bind()函数的值。比如:

一句话总结:

A全call单:apply的参数是数组,而call是单个单个的。他们都是在特定的作用域中调用函数。
Bind是返回绑定特定作用域的一个新的函数。

var o = {color: 'blue'};
function sayColor() {alert(this.color)};
var objColor = sayColor.bind(o);
objColor(); 		// blue

例子

例1: 可用通过打印的this看出,不同的调用,this指向的对象是不一样的。
其中指定null或者正常调用函数,this指向的是全局变量window,而当传入thisArg时,this就指向的是thisArg。从而实现了改变this为你想要的对象。

function fun1(x, y) {
    console.log(x + y);
    console.log('this = ', this);
}

function fun2(x, y) {
    var myName = 'jason';
    console.log(x - y);
}

fun1(3,2)
// 5 <--- result
// this =  Window {frames: Window, postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, …}

fun1.call(null, 3,2)
// 5 <--- result
// this =  Window {frames: Window, postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, …}

fun1.call(fun2, 3, 2)
// 5 <--- result
// this =  ƒ fun2(x, y) {
//    var myName = 'jason';
//    console.log(x - y);
//}

例2:

window.color = 'red';
var o = {color: 'blue'};

function sayColor() {
	alert(this.color);
}

sayColor();		// red
sayColor.call(this); 	// red
sayColor.call(window); 	// red
sayColor.call(o);		// blue

例三: 合并数组

如果你需要合并两个数组,你可以使用Array.concat()函数:

var array1 = [1, 2, 3];  
var array2 = [4, 5, 6];  
console.log(array1.concat(array2)); // [1,2,3,4,5,6];  //不适用大数组

**但是,这个函数对于大数组来说不并合适,因为它将会创建一个新的数组并消耗大量的内存。**在这种情况下,你可以使用Array.push.apply(arr1,arr2),它不会创建一个新数组,而是将第二个数组合并到第一个数组中,以减少内存使用:

var array1 = [1, 2, 3];  
var array2 = [4, 5, 6];  
console.log(array1.push.apply(array1, array2)); // [1,2,3,4,5,6]; 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木瓜~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值