(javascript)es6的的arrow function的scope差别

展示代码:

class P {
    constructor(n) {
        this.n = n
    }


    p() {
        setTimeout(function() { console.log(`this: ${this.n}`) }, 100)
    }

    q() {
        setTimeout(() => console.log(`this: ${this.n}`), 200)
    }
}

let p = new P("x")
p.p()
p.q()

运行结果:

从上面截图可以看到,arrow function和普通function的scope区别:它们的this所指向的object不一样。

My Github Page: https://github.com/liweinan

Powered by Jekyll and Theme by solid

If you have any question want to ask or find bugs regarding with my blog posts, please report it here:
https://github.com/liweinan/liweinan.github.io/issues