Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

call,apply,bind的理解及应用 #15

Open
wl05 opened this issue May 10, 2019 · 0 comments
Open

call,apply,bind的理解及应用 #15

wl05 opened this issue May 10, 2019 · 0 comments

Comments

@wl05
Copy link
Owner

wl05 commented May 10, 2019

总结call,apply,bind的理解及应用

作用

call、apply和bind都可以改变函数运行时this的指向。

区别

call、apply与bind的差别

call,apply 在改变了函数的this后便立即执行函数,而bind,MDN的解释是:bind()方法会创建一个新函数,称为绑定函数,当调用这个绑定函数时,绑定函数会以创建它时传入 bind()方法的第一个参数作为 this,传入 bind() 方法的第二个以及以后的参数加上绑定函数运行时本身的参数按照顺序作为原函数的参数来调用原函数。

call 和 apply 的区别

对于 apply、call 二者而言,作用完全一样,只是接受参数的方式不太一样。call 需要把参数按顺序传递进去,而 apply 则是把参数放在数组里。  

应用

1.数组之间追加

var array1 = [12 , "foo" , {name "Joe"} , -2458];
var array2 = ["Doe" , 555 , 100];
Array.prototype.push.apply(array1, array2);

2. 获取数组中的最大值和最小值

var arr = [34,5,3,6,54,6,-67,5,7,6,-8,687];
Math.max.apply(Math, arr);
Math.max.call(Math, 34,5,3,6,54,6,-67,5,7,6,-8,687);
Math.min.apply(Math, arr);
Math.min.call(Math, 34,5,3,6,54,6,-67,5,7,6,-8,687);

3. 将伪数组转化为数组

Javascript中存在一种名为伪数组的对象结构。比较特别的是 arguments 对象,还有像调用 getElementsByTagName , document.childNodes 之类的,它们返回NodeList对象都属于伪数组。不能应用 Array下的 push , pop 等方法。

但是我们能通过 Array.prototype.slice.call 转换为真正的数组的带有 length 属性的对象,这样 domNodes 就可以应用 Array 下的所有方法了。

var domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));

4. 验证是否是数组

function isArray(obj){
    return Object.prototype.toString.call(obj) === '[object Array]' ;
}

5. 继承

var Person = function (name, age) {
  this.name = name;
  this.age = age;
};
Person.prototype.say = function(){
    console.log('hello')
}
var Girl = function (name) {
  Person.call(this, name);
};
var Boy = function (name, age) {
  Person.apply(this, arguments);
}
var g1 = new Girl ('qing');
var b1 = new Boy('qianlong', 100);

这里需要注意的是Girl,Boy并不会继承Person原型上的say方法。

6. call和apply第一个参数为null时

当apply与call传入的第一个参数为null时,函数体内的this会指向window。

var func = function(a,b,c)
{
    console.log(this,a + b + c);
}
func.apply(null,[1,2,3]);
func.call(null,1,2,3);

参考文章

  1. js中call、apply、bind那些事
  2. 深入浅出妙用 Javascript 中 apply、call、bind
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant