簡體   English   中英

如果未在Typescript對象中定義setter或屬性,則什么也不做?

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM