说一下call、apply、bind区别

说一下call、apply、bind区别

共同点:都是来改变this指向

语法:函数.call 、 函数.apply 、 函数.bind

 

不同点:

1. call和apply是立即执行的。

2. bind返回的是一个函数体,新函数的 this 才会变化,原函数不变,需要()执行函数

3. apply第二个参数是数组,call、bind是多个参数。

 

场景:

1. bind :给dom添加一个事件,事件的赋值肯定是函数,这时候要改变this指向并且返回的函数体,必须使用bind

<button id='btn'>按钮</button>

<div id='text'>你好吗</div>

 

var btn = document.getElementById('btn'),

text = document.getElementById('text');

 

btn.onclick = function(){

console.log( this.id ); //  点击得到text,不会直接执行

}.bind(text)

如果你用apply(text),那么不用点击,就可以直接得到text

 

2. apply 

var arr = [1,4,4,545,3,5,435,3];

console.log( Math.max.apply(this,arr) );

 

3. 剩余情况用call

 
posted @ 2022-05-11 15:25  杨建鑫  阅读(69)  评论(0编辑  收藏  举报