javascript之this

mac2022-06-30  30

this 只依赖于调用函数前的对象

function foo() { console.log(this.a) } var a = 1 foo() var obj = { a: 2, foo: foo } obj.foo() // 优先级是第二个情况大于第一个情况

以下情况优先级最高

var c = new foo() c.a = 3 console.log(c.a) // this` 只会绑定在 `c` 上,不会被任何方式修改 `this` 指向

利用 call,apply,bind 改变 this

这个优先级仅次于 new

箭头函数中的this

function a() { return () => { return () => { console.log(this) } } } console.log(a()()())

箭头函数其实是没有 this 的,这个函数中的 this 只取决于他外面的第一个不是箭头函数的函数的 this。在这个例子中,因为调用 a 符合前面代码中的第一个情况,所以 this 是 window。并且 this 一旦绑定了上下文,就不会被任何代码改变。

转载于:https://www.cnblogs.com/guangzan/p/11270656.html

最新回复(0)