[英]Do nothing if setter or property is not defined in Typescript Object?
Is it possible to check if there is no setter defined in Typescript Object? 是否可以检查Typescript对象中是否未定义设置器?
I have following code: 我有以下代码:
class Sample {
private _name;
set name(value: string) {
value = value.trim();
if(value.length > 0)
this._name = value;
}
get name(): string {
return this._name;
}
}
i set the values by a change listener in my html forms. 我在我的html表单中通过更改侦听器设置值。
the problem is, if i have a form element what shows on a not defined object property it simply sets it. 问题是,如果我有一个在未定义的对象属性上显示的表单元素,它将简单地对其进行设置。
sample = new Sample();
sample.name = "myName";
sample.myTest = true;
returns an object like this: 返回这样的对象:
{
name: "myName";
myTest: true;
}
how can i prevent undefined properties will not be set? 如何防止无法设置未定义的属性?
using sample.hasOwnProperty(propertyName)
allways returns false. 使用
sample.hasOwnProperty(propertyName)
始终返回false。 sample.hasOwnProperty('_' + propertyName)
also returns false. sample.hasOwnProperty('_' + propertyName)
也返回false。
sample[propertyName] === undefined
returns true on sample.name because there is not value set on initializing an object. sample[propertyName] === undefined
在sample.name上返回true,因为在初始化对象时未设置任何值。
You can check if the instance constructor.prototype
has the property: 您可以检查实例
constructor.prototype
是否具有以下属性:
let sample = new Sample();
console.log(sample.constructor.prototype.hasOwnProperty("name")); // true
let object = {};
console.log(object.constructor.prototype.hasOwnProperty("name")); // false
( code in playground ) ( 操场上的代码 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.