js中this的指向是在运行时会变动的
这句话严谨的说是有问题的。
this
这个关键词,在java中的解释是引用当前类的实例变量
。这里有两个关键词当前类
和实例变量
,说白了this
是当前执行方法的调用者
比如
const a = { say() { console.log(this === a); }}a.say(); // true复制代码
再比如
class A { constructor() { this.name = "A"; } say() { console.log(this.name); }}const a = new A();a.say(); // "A"const b = { name: "B", say: a.say}b.say(); // "B"复制代码
但有时,我们会遇到下面?的情况
function sayThis() { // TODO console.log(this);}sayThis();复制代码
一个方法,没有直接调用者。。。。
这种情况的时候,代码的效果就是这样的
function sayThis() { // TODO console.log(this);}this.sayThis();复制代码
如果一个函数没有显式的调用者,那么,这个函数的调用者就是此函数执行的作用域中的this
所以,归根结底,this
是当前执行方法的调用者
?
?
?
?
?
?
?
你以为这样就结束了?Too young too simple
js中还有三个显式绑定this的方法,bind
,apply
,call
当使用这些方法指定执行函数的this时,那this基本上就是指定的了
基本上?有特殊情况吗?
有!!!!?
箭头函数
const sayThis = () => { console.log(this)}复制代码
上面的代码用babel编译之后
var _this = this;var sayThis = function () { console.log(_this);};复制代码
很容易理解箭头函数中this的指向