http://www.javashuo.com/article/p-wrzhlgzs-nb.html (更容易理解的方法)數組
1.爲何要用 call 、apply?
爲了 改變方法裏面的屬性而不去改變原來的方法app
function fruits() {}
fruits.prototype = {
color: "red",
say: function() {
console.log("My color is " + this.color);
}
}
var apple = new fruits;
apple.say(); //My color is red
banana = {
color: "yellow"
}
}
apple.say.call(banana); //My color is yellow
a
apple.say.apply(banana); //My color is yellow
2.call 與apply 區別
1)call 參數固定 apply 參數不固定 apply 參數是放在數組裏面的
2)call 能夠將僞數組轉換爲真正的數組
例如一個例子:函數
function log(){
var args = Array.prototype.slice.call(arguments);
args.unshift('(app)');
console.log.apply(console, args);
};
log("hello world"); //(app)hello world
3) bind 是返回對應函數,便於稍後調用;apply 、call 則是當即調用 。ui
function show(sex){
console.log("普通函數"+sex);
}
var person={
name:"aa",
age:14
};
show.call(person,"男");
show.apply(person,["女"]);
//對於bind來講,用法更加的靈活
show.bind(person,"不明")(
);
// var ss=show.bind(person,"不明");
// ss();