class中的箭头函数会输出什么
记录由于自身太菜而让人产生很多问号的JS行为
看看下面的例子,猜猜会输出什么。
Round1
window.greeting = 'bye'
class A {
greeting = 'hello'
arrow_a = () => { console.log(this.greeting + ' arrow') }
func_a() { console.log(this.greeting + ' bind') }
}
console.log(A.prototype)
let a = new A()
let {arrow_a, func_a} = a
arrow_a()
a.arrow_a()
func_a()
a.func_a()
输出:
{constructor: ƒ, func_a: ƒ}
hello arrow
hello arrow
bind
hello bind
Round2
class B extends A {
arrow_b = () => {
super.arrow_a()
}
func_b() {
super.func_a()
}
}
console.log(B.prototype)
let b = new B()
b.arrow_b()
b.func_b()
输出:
A {constructor: ƒ, func_b: ƒ}
Uncaught TypeError: (intermediate value).arrow_a is not a function
hello bind
Round3
class C extends A {
func_c() {
super.arrow_a()
}
arrow_a() {
super.arrow_a()
}
}
console.log(C.prototype)
console.log(C.prototype.__proto__)
let c = new C()
c.arrow_a()
c.func_c()
输出:
A {constructor: ƒ, func_c: ƒ, arrow_a: ƒ}
{constructor: ƒ, func_a: ƒ}
hello arrow
Uncaught TypeError: (intermediate value).arrow_a is not a function
Round4
class D extends A {}
console.log(D.prototype)
console.log(D.prototype.__proto__)
let d = new D()
d.arrow_a()
输出:
A {constructor: ƒ}
{constructor: ƒ, func_a: ƒ}
hello arrow
- 原文作者:yrq110
- 原文链接:http://yrq110.me/post/front-end/arrow-function-in-class-proporties/
- 版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可,非商业转载请注明出处(作者,原文链接),商业转载请联系作者获得授权。