一、问答
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
本教程版权归小韩同学和饥人谷所有,转载须说明来源
网友评论