1.this是什么?
解析器每次在调用函数时,都会向函数内部传入一个隐含的参数,这个隐含的参数就是this
function fun () {
console.log(this);
}
fun()//window
2.为什么需要用到this?
有些时候我们需要知道是谁调用了函数,方便我们去获取相应的一个值
3.this指向问题
(1)当以函数的形式调用的时候,我们this指向的是window
function fun () {
console.log(this);
}
fun()
(2)当以对象的方法调用的时候,this指向的是调用这个方法的对象
var obj = {
name:'ls',
sayHello:function() {
// console.log(this);//指向obj
return this.name
}
}
// console.log(obj.sayHello);
var result = obj.sayHello()
console.log(result);