this指向
情况1:如果一个函数中有this,但是它没有被上一级的对象所调用,那么this指向的就是window,这里需要说明的是在js的严格版中this指向的不是window。
情况2:如果一个函数中有this,这个函数有被上一级的对象所调用,那么this指向的就是上一级的对象。
情况3:如果一个函数中有this,这个函数中包含多个对象,尽管这个函数是被最外层的对象所调用,this指向的也只是它上一级的对象。
当this遇见new
function test() {
this.username= '王小帅'
}
var instance = new test()
console.log(instance.username) //王小帅
我们发现输出为 ‘王小帅’,那是因为new关键字改变了this的指向。
在这里我们通过new运算符创建的test()对象的实例,并将其赋值给instance,并没有真正执行,真正调用这个对象的是instance,所以this自然指向了instance
当this遇见return
如果返回值是一个对象,那么this就指向返回的对象;
function test(name)
{
this.name = name
return {}
}
var instance = new test('王小帅')
console.log(instance.name) //undefined
function test()
{
this.username = '王小帅';
return function(){};
}
var instance = new test;
console.log(instance.username); //undefined
如果返回不是一个对象,那么this指向函数的实例
function test() {
this.username = '王小帅'
return 1
}
var instance = new test()
console.log(instance.username) //王小帅
function test() {
this.username = '王小帅'
return undefined
}
var instance = new test()
console.log(instance.username) //王小帅
null对象是一个特殊例子,this也是指向函数的实例
function test() {
this.username = '王小帅'
return null
}
var instance = new test()
console.log(instance.username) //王小帅