[英]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.