Node.js 在函数内设置类属性
我知道如何在其中设置类属性:Node.js 在函数内设置类属性,node.js,Node.js,我知道如何在其中设置类属性:this.property=1 但是如果它在一个函数中,我应该怎么做呢? 例如: 这就是arrow函数的用途,它们在函数范围内提供了词法 request(options, (err, res, body) => { this.property = 1 }) 另外,类构造函数中的副作用是一种反模式,特别是异步模式。“this”是一个关键字。它指的是对象。“this.someProperty”是指相关对象的someProperty Test是类名。prop
this.property=1
但是如果它在一个函数中,我应该怎么做呢?
例如:
这就是arrow函数的用途,它们在函数范围内提供了词法
request(options, (err, res, body) => {
this.property = 1
})
另外,类构造函数中的副作用是一种反模式,特别是异步模式。“this”是一个关键字。它指的是对象。“this.someProperty”是指相关对象的someProperty
Test是类名。property是处理对象属性的错误方法
如上所述,从函数中寻址属性的正确方法是使用arrow函数
class Test = {
constructor(){
var request = require('request');
request(options, (err, res, body)=>{
this.property = 1
})
}
}
var aTest = new Test(); // a Test object
var anotherTest = new Test(); // another Test object
// Change the property value of the objects
aTest.property = 5
anotherTest.property = 10
我对js不是很在行,所以这可能不是最好的解决方案,但我很确定你可以做一些类似于
const self=this
在匿名函数之外,然后使用self.property=1进行设置代码>在函数内部时。@Addison是的,它可以工作,就像Test.property=1代码>也是。也许有人解释了两者的区别,什么是更好的,但不清楚你们当时想要达到什么Test.property
和this.property
是苹果和桔子。是否要设置实例或静态属性?我刚刚发现此页面解释了此问题的各种解决方法:。这绝对值得一看。通过阅读该部分,似乎使用严格模式也解决了这个问题(尽管我仍然最喜欢@estus的答案,因为它看起来更好,而且不依赖于知道js将运行在哪里)。感谢您的回答。正是我想要的。关于构造函数中的异步函数。如果我想在调用newtest()
之后发出请求,我应该怎么做?我通常有显式的类方法,比如fetch
,并显式地调用它。即使这是在构造函数中完成的,在构造函数中有回调参数也是一个很好的实践,因此可以通知类外的代码初始化已经完成。但当您从回调切换到承诺(我建议尽快这样做)时,很明显单独的fetch
方法工作得更好。再次感谢。你帮了大忙。
class Test = {
constructor(){
var request = require('request');
request(options, (err, res, body)=>{
this.property = 1
})
}
}
var aTest = new Test(); // a Test object
var anotherTest = new Test(); // another Test object
// Change the property value of the objects
aTest.property = 5
anotherTest.property = 10