简体   繁体   English

JS 对象字面量“new”中回调函数的范围

[英]Scope of callback function in "new" on JS object literal

In this code, the callback function receives the scope of the new Thing object (as the commend shows, Thing is logged.) Use of an arrow function causes it to log the window object.在这段代码中,回调函数接收新Thing对象的范围(如命令所示, Thing被记录。)使用箭头函数会导致它记录 window 对象。

I'd like to be able to access the scope of the literal object in that callback function, ideally without referring to it from the global object.我希望能够访问该回调函数中literal对象的范围,理想情况下不从全局对象中引用它。 Is there some way to do this?有没有办法做到这一点?

function Thing(fun){
    this.funThing = fun
}

let literal = {
    thing: new Thing(function(){
        console.log(this)
    })
}

literal.thing.funThing() // Thing {funThing: ƒ}

You could use a getter instead, main difference here would be that upon each access the thing would be recreated, but well, that you could overcome in a different way ;)您可以使用 getter 代替,这里的主要区别在于每次访问时都会重新创建事物,但是,您可以以不同的方式克服;)

And yes, I changed it to an arrow function here, but I could have bound the callback function as well是的,我在这里将其更改为箭头函数,但我也可以绑定回调函数

 function Thing(fun){ this.funThing = fun } let literal = { get thing() { return new Thing(() => { console.log(this) }); } } literal.thing.funThing()

Solution of lcepickle works fine. lcepickle 的解决方案工作正常。 Another way is to bind the callback function with the literal object, but in this case you have to define it before calling new Thing constructor.另一种方法是将回调函数与文字对象绑定,但在这种情况下,您必须在调用new Thing构造函数之前定义它。 So, you can add the thing attribute after the definition of literal object:因此,您可以在定义字面量对象之后添加thing属性:

function Thing(fun){
    this.funThing = fun
}

let literal = { }
literal.thing = new Thing(function(){
    console.log(this)
}.bind(literal))

literal.thing.funThing()

You could bind the anonymous callback function to the scope of the literal object.您可以将匿名回调函数绑定到literal对象的范围。

 function Thing(fun){ this.funThing = fun } literal = { thing: new Thing(function(){ console.log(this) }.bind(this.literal)) } literal.thing.funThing()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM