Tryam
Tryam

Reputation: 405

Set class property inside function

I know how to set class property inside it: this.property = 1.

But what should I do if it's inside a function? Example:

class Test = {
    constructor(){
        var request = require('request');
        request(options, function(err, res, body){
            // Here I want to set Test property
            // Something like this.property = 1 or 
            // Test.property = 1
        }
    }
}

Upvotes: 1

Views: 2027

Answers (2)

gkont
gkont

Reputation: 199

"this", is a keyword. It refers to the object. "this.someProperty", means the concerned object's someProperty property.

Test is the class name. Test.property is simply wrong way to address an object's property.

As noted above, the right way to address the property from within a function is to use an arrow function.

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

Upvotes: 0

Estus Flask
Estus Flask

Reputation: 222409

This is what arrow functions are for, they provide lexical this in function scope.

request(options, (err, res, body) => {
    this.property = 1
})

Also, side effects in class constructor is an antipattern, especially asynchronous ones.

Upvotes: 3

Related Questions