This是在运行时确定的,一下所有的情况都是在函数执行时确定this
function this问题
如果函数有明确的归属对象,则this指向对象。
function Person(){
this.hi = function(){
console.log(this);
}
}
Var p = new Person(); p.hi是p的成员函数,hi中的this指向p。
如果说var b = p.hi执行b()则会输出global,因为b是全局的,归属global
如果这样声明
function hi(){
console.log(this);
}
hi函数没有明确的归属关系,就编程顶层对象的成员函数node就是global.hi(浏览器就是window.hi).
ES6中class中的this
Class A{
Click(){
Console.log(this);
}
}
a= new A()
a.click() //会输出对象a
//但是如果这样b=a.click执行b()那么则会输出undefine