![](/img/trans.png)
[英]Why does a javascript object property assignment via the dot notation NOT trigger a setter defined for that property?
[英]Do nothing if setter or property is not defined in Typescript Object?
是否可以检查Typescript对象中是否未定义设置器?
我有以下代码:
class Sample {
private _name;
set name(value: string) {
value = value.trim();
if(value.length > 0)
this._name = value;
}
get name(): string {
return this._name;
}
}
我在我的html表单中通过更改侦听器设置值。
问题是,如果我有一个在未定义的对象属性上显示的表单元素,它将简单地对其进行设置。
sample = new Sample();
sample.name = "myName";
sample.myTest = true;
返回这样的对象:
{
name: "myName";
myTest: true;
}
如何防止无法设置未定义的属性?
使用sample.hasOwnProperty(propertyName)
始终返回false。 sample.hasOwnProperty('_' + propertyName)
也返回false。
sample[propertyName] === undefined
在sample.name上返回true,因为在初始化对象时未设置任何值。
您可以检查实例constructor.prototype
是否具有以下属性:
let sample = new Sample();
console.log(sample.constructor.prototype.hasOwnProperty("name")); // true
let object = {};
console.log(object.constructor.prototype.hasOwnProperty("name")); // false
( 操场上的代码 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.