作为一名新人,第一次在博客上写东西,可能很多东西不完整,也可能会出现很多的错误,希望大家能给予改正和包容。
刚刚了解了apply,call和bind,就来写一点东西加深印象。
大家都知道call,apply和bind最大的作用是扩充函数的作用域,改变this的指向,那我们就开看一下它们之间的相同与区别。
var o={
name:'cj',
printf:function(name){
this.name=name;
}
}
function Person(name){
o.apply(this,arguments); //输出Bob
o.call(this,name); //输出Bob
o.bind(this)(name); //输出Bob
}
var p1=new Person('Bob');
console.log(p1.name);
在上述代码中,apply中传入的是一个数组,而call传入的是具体参数,bind则是绑定函数,需要自己调用,如o.bind(this)(name),this指向Person而name则是传入要执行函数的值。
另一方面call和apply会在执行的时候就调用,而bind则是返回对应的函数。
补:当在非严格模式下直接在函数内调用call或apply传入this时,this指向函数的window对象,或者传入null或undefined时,会转换为全局变量window,node下则会转换为golbal,当在严格模式下则不会发生类型转换,this变为undefined,null或undefind则就是本身
function sum1(e,r){
alert( this);
}
function sum2(sum3,sum2){
sum1.apply(this,arguments);
}
sum2(1,2) //[object Window]
//null 和undefined 也是这样,发生隐式转换
"use strict"
function sum2(sum3,sum2){
sum1.apply(this,arguments);//undefined (严格模式下,为指明环境对象调用this,this不
//会转换为window
}
function sum2(sum3,sum2){
sum1.apply(null,arguments); //弹出null,undefind弹出undefined,严格模式不会转换
}