Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 在函数内设置类属性_Node.js - Fatal编程技术网

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