一,js中的上下文this
1,指向函数拥有者
2,只能在函数内部使用
二,各种场景使用
1,对象声明(this指向对象)
var pet = {
words: '...',
speak: function() {
console.log(this.words)
console.log(this === pet)
}
}
pet.speak()
执行结果
...
true
2,函数声明(this指向global(或window))
function pet(words){
this.words = words
console.log(this.words)
console.log(this === global)
}
pet('...')
执行结果
...
true
3,构造函数声明(this指向新声明的对象)
function Pet(words) {
this.words = words
this.speak = function() {
console.log(this.words)
console.log(this)
}
}
var cat = new Pet('Miao')
cat.speak()
执行结果
Miao
Pet { words: 'Miao', speak: [Func]}
三,call和apply
1,半替换
var pet = {
words: '...',
speak: function(say) {
console.log(say + ' ' + this.words)
}
}
// pet.speak('Speak')
var dog = {
words: 'Wang'
}
pet.speak.call(dog, 'Speak')
//call把this由pet指向了dog,所以
//执行结果
//Speak Wang
2,全替换
function Pet(words) {
this.words = words
this.speak = function() {
console.log(this.words)
}
}
function Dog(words) {
Pet.call(this, words)
// Pet.apply(this, arguments)
}
var dog = new Dog('Wang')
dog.speak()
//this由Pet指向Dog,相当于构造函数整个继承。
//执行结果
//Wang