我了解在JavaScript class
es中有一个名为“属性初始化程序语法”的新语法的TC-39提案。
我还没有找到很多这方面的文档,但在讨论React时它用于egghead课程。
class Foo {
bar = () => {
return this;
}
}
此提案的目的是什么?它与以下内容有何不同:
class Foo {
bar() {
return this;
}
}
答案 0 :(得分:5)
当您使用属性初始化程序语法和箭头函数时,此函数中的data %>%
complete(user_id, aisle_id = 1:21, fill = list(n = 0)) %>%
mutate(aisle_id = paste0("aisle_", formatC(aisle_id, width = 2, flag = 0))) %>% spread(aisle_id, n)
# A tibble: 2 × 22
user_id aisle_01 aisle_02 aisle_03 aisle_04 aisle_05 aisle_06 aisle_07 aisle_08 aisle_09 aisle_10 aisle_11 aisle_12
* <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 0 8 12 5 0 0 0 0 0 0 0 0
2 2 1 0 6 0 0 0 0 0 0 0 0 0
# ... with 9 more variables: aisle_13 <dbl>, aisle_14 <dbl>, aisle_15 <dbl>, aisle_16 <dbl>, aisle_17 <dbl>, aisle_18 <dbl>,
# aisle_19 <dbl>, aisle_20 <dbl>, aisle_21 <dbl>
将始终引用该类的实例,而使用常规方法,您可以使用{{1}更改this
}或this
:
.call()
&#13;
此外,此语法可用于除函数之外的其他内容。
答案 1 :(得分:0)
从不同的角度来看,您可以使用Property initializer语法作为构造函数中详细的方法绑定的简写。
另请注意,语法也可用于变量。
class Property {
v = 42
bar = () => {
return this.v
}
}
// --------
class Bound {
constructor() {
this.v = 43
this.bar = this.bar.bind(this)
}
bar() {
return this.v;
}
}
// --------
class Classic {
constructor() {
this.v = 44
}
bar() {
return this.v;
}
}
,
const allBars = [
new Property().bar,
new Bound().bar,
new Classic().bar
]
console.log([
allBars[0](),
allBars[1](),
allBars[2]()
])
// prints: [42, 43, undefined]
在allBars数组中未定义属性v
,其中this
未绑定bar
点,因为它是从其上下文调用的。