0

My createCon function uses this to set the con for this object. I am getting this to be undefined. Error: Can not set property of 'con' of undefined. What is the best of being able to reference this from the objects functions?

class parent {
    constructor(stringA, stringB){
        this.config = {};
        this.con = {};
    }
}

class child extends parent {
    constructor(stringA, stringB) {
        super(stringA,stringB)
        this.config = {
            full : stringA+stringB
        }
    }

    createConn(){
        var con = con(this.config.full);
        con.connect(function(err){
            if(!err) this.con = con;
        })
    }
}
clearner
  • 15
  • 4
  • @MikeMcCaughan This is not a scope issue. It is a binding issue. The behaviour of `this` is specified separately from variable scopes. – slebetman May 22 '17 at 22:04

1 Answers1

1

You are using the this keyword inside of a function. this is not like other OOP languages and refers to a 'context', which can change based on the execution of the function.

You want to use an arrow function, which will lexically bind (i.e, preserve) the this of the context where the arrow function is defined.

createConn(){
    var con = con(this.config.full);
    con.connect((err) => {
        if(!err) this.con = con;
    })
}
Dan
  • 10,282
  • 2
  • 37
  • 64