每個函數(shù)都包含兩個非繼承而來的方法:call()方法和apply()方法。
-
相同點:這兩個方法的作用是一樣的。
3.改變this的指向
4.繼承別的函數(shù)中的實例(對象冒充)
<script>
window.color = 'green';
document.color = 'yellow';var s1 = {color: 'blue' }; function changeColor(){ console.log(this.color); } changeColor.call(); //green (默認(rèn)傳遞參數(shù)) changeColor.call(window); //green changeColor.call(document); //yellow changeColor.call(this); //green changeColor.call(s1); //blue
</script>
//例2
var Pet = {
words : '...',
speak : function (say) {
console.log(say + ''+ this.words)
}
}
Pet.speak('Speak'); // 結(jié)果:Speak...var Dog = {
words:'Wang'
}//將this的指向改變成了Dog
Pet.speak.call(Dog, 'Speak'); //結(jié)果: SpeakWang
apply()方法使用示例:
//例1
<script>
window.number = 'one';
html.number = 'two';
var qq = {number: 'three' };
function changeColor(){
console.log(this.number);
}
changeColor.apply(); //one (默認(rèn)傳參)
changeColor.apply(window); //one
changeColor.apply(html); //two
changeColor.apply(this); //one
changeColor.apply(qq); //three
</script>
//例2
function Pet(words){
this.words = words;
this.speak = function () {
console.log( this.words)
}
}
function Dog(words){
//Pet.call(this, words); //結(jié)果: Wang
Pet.apply(this, arguments); //結(jié)果: Wang
}
var dog = new Dog('Wang');
dog.speak();
call與apply的區(qū)別
1.第一個參數(shù)相同,后面的call要逐一列舉apply放在數(shù)組中
例子1
function add(c,d){
return this.a + this.b + c + d;
}
var s = {a:1, b:2};
console.log(add.call(s,3,4)); // 1+2+3+4 = 10
console.log(add.apply(s,[5,6])); // 1+2+5+6 = 14
- bind()方法會創(chuàng)建一個新函數(shù),稱為綁定函數(shù),當(dāng)調(diào)用這個綁定函數(shù)時,綁定函數(shù)會以創(chuàng)建它時傳入 bind()方法的第一個參數(shù)作為 this,傳入 bind() 方法的第二個以及以后的參數(shù)加上綁定函數(shù)運行時本身的參數(shù)按照順序作為原函數(shù)的參數(shù)來調(diào)用原函數(shù)。
var bar = function(){
console.log(this.x);
}
var foo = {
x:3
}
bar(); // undefined
var func = bar.bind(foo);
func(); // 3
當(dāng)你希望改變上下文環(huán)境之后并非立即執(zhí)行,而是回調(diào)執(zhí)行的時候,使用 bind() 方法。而 apply/call 則會立即執(zhí)行函數(shù)。
最后總結(jié):
apply 、 call 、bind 三者都是用來改變函數(shù)的this對象的指向的;
apply 、 call 、bind 三者第一個參數(shù)都是this要指向的對象,也就是想指定的上下文;
apply 、 call 、bind 三者都可以利用后續(xù)參數(shù)傳參;
bind 是返回對應(yīng)函數(shù),便于稍后調(diào)用;apply 、call 則是立即調(diào)用 。