1、apply,call都是为了改变函数运行时的上下文而存在的,也就是常说的this指向
function fruits() {}
fruits.prototype = {
color: "red",
say: function() {
console.log("My color is " + this.color);
}
}
var object = new fruits;
object.say(); //My color is red
//当了另一个对象需要使用say方法的时候可以不用重新定义
var otherObject = {
color : " yellow""
};
//这时候可以利用call/apply
object.say.call(otherObject); //My color is yellow
object.say.apply(otherObject); //My color is yellow
2、 call和apply的区别:两者作用相同,只是接收参数的方式不同,call 需要把参数按顺序传递进去,而 apply 则是把参数放在数组里
var array1 = [12 , "foo" , {name:"Joe"} , -2458];
var array2 = ["Doe" , 555 , 100];
Array.prototype.push.apply(array1, array2);
// array1 值为 [12 , "foo" , {name:"Joe"} , -2458 , "Doe" , 555 , 100]
常用的,判断某个对象是否是数组:
Object.prototype.toString.call(obj) //如果是则会输出 '[object Array]'
还有伪数组转换为数组
Array.prototype.slice.call(document.getElmentsByTagName("*"))
3、bind方法
this.num = 9;
var mymodule = {
num: 81,
getNum: function() {
console.log(this.num);
}
};
mymodule.getNum(); // 81
var getNum = mymodule.getNum;
getNum(); // 9, 因为在这个例子中,"this"指向全局对象
var boundGetNum = getNum.bind(mymodule);
boundGetNum(); // 81
上边这个方法其实就是改变了this的指向,工作中我们常用_this或者that保存this,不妨使用bind方法更优雅的解决这个问题
例如:
var foo = {
bar : 1,
eventBind: function(){
$('.someClass').on('click',function(event) {
/* Act on the event */
console.log(this.bar); //1
}.bind(this));
}
}
上面这个例子使用bind改变的this的指向,在不改变之前是指向背点击的元素的,是没有bar属性的,就需要使用_this或者that来保存this了
三者都可以改变this的指向