1.函数的this指向是谁调用就指向谁
全局下的函数(window)
function test(){
var s = 's'
console.log(this.s)
}
test() // undefined
因为此时 test()等价于 window.test()
所以this指向了window window.s自然是undefined
对象的函数
var o = {
test: function() {
console.log(this.s)
},
s: 's'
}
o.test() // s
此时this指向了o
对象的对象的函数
var o = {
s: 's',
oo: {
s: 'ss',
test: function() {
console.log(this.s)}
}
}
o.oo.test() // ss
此时最终是oo调用了test所以this指向oo
特殊的用法
var o = {
s: 's',
oo: {
s: 'ss',
test: function() {
console.log(this.s)}
}
}
var test = o.oo.test
test() // undefined
因为此时就是window在调用test
构造函数的this
function F() {
this.name = 's'
this.test = function() {
console.log(this.name)}
}
var f = new F()
f.test() // s
因为F里面的this指向了f
参考前面写过的new操作符
帮你回忆下
封装一个mynew
function mynew(fn) {
var o = {
}
o.