1

Here is a simplified class. I try to loop over key values in constructor, to dynamically assign values to this. But it doesn't work. Is it a syntax problem ? Or is it not possible ?

class DirectoryModel {

    public link_title: string
    public link_desc: string

    constructor(fields: any) {
        console.log(fields) // ok
        _.forOwn(fields, function (value, key) {
            console.log(key) // ok
            console.log(value) // ok
            this[key] = value // "Cannot set property 'link_title' of undefined"
        })

       // this.link_title = fields.link_title
       // this.link_desc = fields.link_desc
    }
}
1
  • 1
    Don't you need the bind that function? Otherwise its this will probably be window. Commented May 4, 2016 at 11:13

1 Answer 1

1

As Yasser commented, this is not bound to your DirectoryModel. Use arrow functions to bind this to your instance:

class DirectoryModel
{

    public link_title: string
    public link_desc: string

    constructor(fields: any)
    {
        _.forOwn(fields, (value, key) => //This binds `this`
        {
            this[key] = value
        })
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.