this指向: 简单的一句话,谁调用的函数,this就指向谁
例子:
var obj = {
fun1: function() {
console.log(this)
}
}
obj.fun1() // 此时obj调用的fun1方法,所以this指向obj
var fun2 = obj.fun1() // obj.fun1()赋给了fun,将结果赋值给了fun2,fun2只是用来输出结果;在赋值给fun2,this已经确定了,因为函数已经执行了,此时this已经是foo了,这是把这个结果保存到了fun2,this还是指向obj
var fun3 = obj.fun1
fun3() // 将obj.fun1赋值给了fun3,此时fun3 = function() { console.log(this) },所以此时this指向的就是window
var fun4 = function() {
console.log(this)
}
fun4() // 此时this也是指向window
call、apply可以改变this指向
例一:(call与apply相同点)
function Person() {
this.name = "小明"
this.like = "play basketball"
this.say = function() {
console.log(this)
console.log(this.name + "喜欢" + this.like)
}
}
function Man() {
this.name = "man"
this.say = function() {
console.log(this)
console.log(this.name)
}
}
var man1 = new Person()
man1.say() //小明喜欢play basketball 此时this指向Person
man1.say.call(Man) //man喜欢undefined 此时this指向Man,所以this.like为undefined
man1.say.apply(Man) //man喜欢undefined 此时this指向Man,所以this.like为undefined
例二:(call与apply不同点)
function ParentDog() {
this.name = "大黄"
this.color = '黄色'
this.say = function() {
console.log(this.name + "的毛是" + this.color + "的")
}
}
function SonDog() {
// ParentDog.call(this, this.name, this.color) // call 参数列表字符串的形式
ParentDog.apply(this, [this.name]) // apply 参数列表是写进数组里
// this.name = "小黄"
this.color = '黑色'
this.sound = "汪汪汪"
this.say = function() {
console.log(this.name + "的毛是" + this.color + "的,整天在大门口" + this.sound + "的叫着")
}
}
var dog = new SonDog()
dog.say()








网友评论