简体   繁体   English

在打字稿类构造函数中将值动态设置为“this”

[英]Dynamically set values into "this" in typescript class constructor

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
    }
}

As Yasser commented, this is not bound to your DirectoryModel.正如 Yasser 所评论的, this与您的 DirectoryModel 无关。 Use arrow functions to bind this to your instance:使用箭头功能绑定this到您的实例:

class DirectoryModel
{

    public link_title: string
    public link_desc: string

    constructor(fields: any)
    {
        _.forOwn(fields, (value, key) => //This binds `this`
        {
            this[key] = value
        })
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 typescript 在构造函数中动态设置 class 属性 - Use typescript to dynamically set class property in constructor 在 TypeScript 中动态返回类构造函数 - Dynamically return a class constructor in TypeScript Typescript是否在类构造函数中设置接口属性? - Does Typescript set interface properties in the Class Constructor? 从构造函数初始化Typescript类值 - Initializing Typescript class values from constructor Angular Typescript 为 class 属性动态赋值 - Angular Typescript assign values to class properties dynamically TypeScript方法中如何动态设置构造函数类型function - How to dynamically set the type of constructor function method in TypeScript 如何从Typescript中的构造函数动态声明类的实例属性? - How to dynamically declare an instance property of a class from a constructor in Typescript? Typescript Map class 构造函数,其初始值不接受 2 种不同类型 - Typescript Map class constructor with initial values not accepting 2 different types 您可以将整个“ this”关键字设置为Typescript类的构造函数中的对象吗? - Can you set the entire “this” keyword to an object in the constructor of a class for Typescript? 打字稿,为类中的可选参数设置默认值 - Typescript, set default values for optional parameters in class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM