提问人:mikekoscinski 提问时间:3/9/2021 更新时间:3/10/2021 访问量:99
如何实现递归方法在对象初始化?
How to implement recursive method **at** object initialization?
问:
假设我有以下对象:
const dog = {
sound: 'woof',
speak: function() {
console.log(this.sound)
}
}
如何在初始对象字面量声明中递归实现?dog.speak
我可以通过在初始对象文字之外定义方法来实现此目的。例如:dog.speak
const dog = {
sound: 'woof'
}
const dog.speak = () => {
console.log(dog.sound)
window.setTimeout(dog.speak, 1000)
}
这之所以有效,是因为这里没有概念 - 该属性明确属于 。但我更愿意在初始对象文字中定义这一切。this
sound
dog
为此,我需要通过 保留上下文。但是我正在努力确定在进行递归函数调用之前的位置。this
.bind()
.bind()
dog
this
答:
0赞
mikekoscinski
3/9/2021
#1
const dog = {
sound: 'woof',
speak: function() {
console.log(this.sound)
const speak = this.speak.bind(dog)
window.setTimeout(speak, 1000)
}
}
这将在单个对象文本中实现目标。
我们可以在初始函数调用中使用 as,这会在以后的所有函数调用中保留上下文。bind
dog
this
this
先前的尝试,例如:
const dog = {
sound: 'woof'
}
const dog.speak = () => {
console.log(dog.sound)
window.setTimeout(dog.speak, 1000)
}
在第一次函数调用后将丢失其上下文。 将在第一个函数调用时引用,然后在以后的调用中引用。this
this
dog
window
评论
1赞
VLAZ
3/9/2021
您也可以只使用箭头函数。我更喜欢它,因为否则(或其任何变体)看起来像一个三明治。这是正确的,但很奇怪,因为该方法周围的对象重复。dog.speak.bind(dog)
this.foo.bind(this)
1赞
Mulan
3/10/2021
#2
箭头函数
首选方法是使用具有词法上下文的箭头函数,this
-
// ECMAScript >= 6
const dog = {
sound: 'woof',
speak: function() {
console.log(this.sound)
setTimeout(_ => this.speak(), 1000)
}
}
dog.speak()
woof
woof
woof
...
函数.prototype.bind
在箭头函数之前,首选将函数转换为上下文 -.bind
// ECMAScript >= 5
const dog = {
sound: 'woof',
speak: function() {
console.log(this.sound)
setTimeout(this.speak.bind(this), 1000)
}
}
dog.speak()
woof
woof
woof
...
上下文变量
在可用之前,您可以将上下文存储在变量中 -.bind
// ECMAScript < 5
const dog = {
sound: 'woof',
speak: function() {
console.log(this.sound)
var ctx = this
setTimeout(function() { ctx.speak() }, 1000)
}
}
dog.speak()
woof
woof
woof
...
或者直接使用——dog
// ECMAScript < 5
const dog = {
sound: 'woof',
speak: function() {
console.log(this.sound)
setTimeout(function() { dog.speak() }, 1000)
}
}
dog.speak()
woof
woof
woof
...
评论
0赞
Bergi
3/10/2021
而不是上下文变量,直接引用即可ctx
dog
0赞
Mulan
3/10/2021
著名的。感谢您的评论^^
评论