-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
1: apply、call 、bind有什么作用,什么区别
作用:指定this,改变作用域.
apply与call相似,不同点在于:apply接受数组作为函数参数,call函数执行的参数必须是一个一个添加
bind生成一个新的函数,新函数中的第一个参数为thhis指向.
2: 以下代码输出什么?
var john = {
firstName: "John"
}
function func() {
alert(this.firstName + ": hi!")
}
john.sayHi = func
john.sayHi()//John:hi!
this指向要看执行时的环境,本题中john对象的sayHi方法调用,this指向john这个对象
3: 下面代码输出什么,为什么
func() //输出window,在全局作用域执行,this指向window
function func() {
alert(this)
}
输出window,在全局作用域执行,this指向window
4:下面代码输出什么
document.addEventListener('click', function(e){
console.log(this);//document
setTimeout(function(){
console.log(this);//window
}, 200);
}, false);
多层this,this指向会变为顶层对象,此时应该将that=this将this赋值使用或者使用箭头函数绑定this
5:下面代码输出什么,why
var john = {
firstName: "John"
}
function func() {
alert( this.firstName )
}
func.call(john)//John,call改变this指向,指向john这个对象
输出John
call改变this指向,指向john这个对象
6: 以下代码有什么问题,如何修改
var module= {
bind: function(){
var that = this//将this在这层函数里将this传递给变量
$btn.on('click', function(){
console.log(this) //this指什么,this指向window,多层this,this指向会变为顶层对象
this.showMsg();
})
},
showMsg: function(){
console.log('Leon');
}
}
//修改后
var module= {
bind: function(){
var that = this//将this在这层函数里将this传递给变量
$btn.on('click', function(){
console.log(that)
this.showMsg();
})
},
showMsg: function(){
console.log('Leon');
}
}
Metadata
Metadata
Assignees
Labels
No labels