老生常谈的问题:call ,apply 与 bind

1.  三个都是函数自带的方法,用于改变函数的this指向(即改变函数作用域)。

2.  call 与 apply 用法类似, 略有区别

func.apply(thisObj, [arg1,arg2,arg3])
func.call(thisObj, arg1, arg2, arg3)

  相同点:  第一个参数都是thisObj,  代表函数func 运行时指定的this

 PS  thisObj并不一定是该函数执行时真正的this值,非严格模式下:

  1)thisObj不传或者为null 或undefined,会自动指向全局对象(window),

  2)thisObj 为原始值(数字,字符串,布尔值)会指向该原始值的自动包装对象。

function a(){   
  console.log(this);   //输出函数a中的this对象
}       

function b(){}       

var c={name:"call"};    //定义对象c  

a.call();   //window
a.call(null);   //window
a.call(undefined);   //window
a.call(1);   //Number
a.call('');   //String
a.call(true);   //Boolean
a.call(b);   //function b(){}
a.call(c);   //Object

  不同点:call()方法接受的是参数列表,apply()方法接受的是一个参数数组

   3. 应用场景

用 apply 将数组添加到另一个数组

var array = ['a', 'b'];
var elements = [0, 1, 2];
array.push.apply(array, elements);
console.info(array); // ["a", "b", 0, 1, 2]

应用(apply) Math.min/Math.max 内置函数求解最大值,最小值

var max = Math.max.apply(null, numbers); /* 基本等同于 Math.max(numbers[0], ...) 或 Math.max(5, 6, ..) */
var min = Math.min.apply(null, numbers);

 

 4. bind()方法创建一个新的函数,在调用时设置this关键字为提供的值。并在调用新函数时,将给定参数列表作为原函数的参数序列的前若干项。

function.bind(thisObj, arg1, arg2, arg3)

PS  1) 与call apply 不同 , bind  返回值时一个函数,apply 与 call 是将原来的函数在新作用域下调用一次。

        2) 与call apply 不同, bind  返回的新函数, 并且新函数的作用域保存不变(被绑定了)

var a =1;
var b=2;
function f() {console.log(this.a,this.b)};
var c = {a:3,b:4};

var d = f.bind(c)
d() // 3 4
f() // 1 2

function f(x,y) {console.log(this.a,this.b,x,y)};
var d = f.bind(c)
d()        //  3 4 undefined undefined
var d = f.bind(c,5,6)
d()       //   1 3 4 5 6
d(7,8)    //  3 4 5 6
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值