一、問答
1.apply、call 有什么作用,什么區別?
call和apply都能改變執行上下文(this的指向),它們唯一的區別是傳遞參數的方式不同,call是一個一個的傳遞參數,而apply是傳遞一組數組或者類數組對象作為參數
示例:
apply
function getMin(){
return Math.min.apply(null,arguments); //這里我們無法確切知道參數是幾個,使用apply
}
console.log(getMin(1,2,3,4)); //1
call
function join(str){
return Array.prototype.join.call(str); //參數只有一個,是確定的使用call
}
console.log(join("hello")) // "h,e,l,l,o"
二、代碼
1.當函數作為對象的方法調用時 this指代當前對象
var john = {
firstName: "John"
}
function func() {
alert(this.firstName + ": hi!")
}
john.sayHi = func
john.sayHi() // "John:hi"
2.在函數被直接調用時this綁定到全局對象
func()
function func() {
alert(this) // [object Window]
}
3.內部嵌套函數的this不是父函數 而是全局對象
function fn0(){
function fn(){
console.log(this); //Window
}
fn();
}
fn0();
4.在事件處理程序中this代表事件源DOM對象(低版本IE有bug,指向了window)
setTimeout和setInterval 這兩個方法執行的函數this也是全局對象
document.addEventListener('click', function(e){
console.log(this); //document
setTimeout(function(){
console.log(this); //Window
}, 200);
}, false);
- call函數的第一個參數就是函數執行上下文,就是this的值
var john = {
firstName: "John"
}
function func() {
alert( this.firstName ) //join
}
func.call(john)
6.call函數的第二個參數以后就是func的入參
var john = {
firstName: "John",
surname: "Smith"
}
function func(a, b) {
alert( this[a] + ' ' + this[b] )
}
func.call(john, 'firstName', 'surname') // "John Smith"
7.以下代碼有什么問題,如何修改?
var module= {
bind: function(){
$btn.on('click', function(){
console.log(this) //this指什么 this指代的是$btn
this.showMsg();
})
},
showMsg: function(){
console.log('饑人谷');
}
}
this.showMsg()中的this指代的$btn 而不是module,應改為
var module= {
bind: function(){
var me=this;
$btn.on('click', function(){
me.showMsg();
})
},
showMsg: function(){
console.log('饑人谷');
}
}
參考文檔:
饑人谷課件-this
阮一峰blog
本教程版權歸小韓同學和饑人谷所有,轉載須說明來源