this指向

90 阅读1分钟

this 等于谁,不取决于它所在的位置 取决于它所在的function是怎么被调用的

方法中的this 谁调用 就指向谁

function yo() {
	console.log('yo, im:' + this.name)
}
var whh = {
	name: '王花花'
}
var lsd = {
	name: '李栓蛋'
}
whh.yo = yo
whh.yo()  // 'yo, im 王花花'

this 代表父级对象 person

var person = {
	firstName: '花花',
	lastName: '王',
	fullName: function () {
    	    return this.lastName + this.firstName // this 代表父级对象 person
	}
}
console.log(person.fullName())

this 代表父级对象 a

var person = {
	firstName: '花花',
	lastName: '王',
	a: {
	    fullName: function () {
        	return this.lastName + this.firstName // this 代表父级对象 a
    	    }
	}
}
console.log(person.a.fullName())

构造函数的this

function User() {
	console.log(this)  // 构造函数中的this就指向,即将生成的对象
	this.name = 'whh'
	this.age = 18
}
User() //  this == undefined
var whh = new User() 
console.log(whh)  // name: whh , age 18