this是函数运行中,自动生成的一个对象(我们在于编译中就已经了解了这一点),随着函数应用场合的不同,this的指向也会有所不同,但有一个原则,this指向调用这个函数的对象。
1.在全局作用域下或普通函数调用 this 指向window
function test(){
console.log(this)
}
test();
console.log(this);
//window
//window
准确来说上述例子应该是window.test() window.console.log(this),按照我们的原则,this理所应当指向window.
2.在对象中作为方法被调用时,this指向调用其的对象
var person={
name:'haha',
age:18,
say:function(){
console.log(this)
}
}
person.say();
//person
3.在构造函数中,this指向new出来的实例(这一点我在之前的构造函数时有提到)
function Person(name){
this.name=name
console.log(this)
}
var person=new Person('hehe')
// person
1158

被折叠的 条评论
为什么被折叠?



