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