从NodeJs中的对象调用时检查类属性是否存在

问题描述 投票:0回答:1

我正在使用nodeJs,在这里创建class,我希望当此类中不存在任何被调用的属性时,它将在控制台中显示警告,我该怎么做?也许使用某种类的函数,但我什么也找不到。

Class Audio

class User {
 constructor(name, age){
    this.name = name;
    this.age = age;
 }
}


// Calling the class 
user = new User('name', 25);
user.height; // This value not exist in class

当有人调用类中不存在的height属性时,我想在控制台中打印警告,如果可以,请告诉我。

node.js ecmascript-6 es6-modules es6-class
1个回答
0
投票

这不是使用JavaScript的正确方法。您可以使用hasOwnProperty方法检查其是否存在。

user = new User('name', 25);
if(user.hasOwnProperty('height')){
   user.height; // This value not exist in class
} else {
console.error("Property does not exist on object")
}

另一种方法是,您可以具有一个访问任何属性的类方法。

class User {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  getProperty(name) {
    if (this.hasOwnProperty(name)) {
      return this[name];
    } else {
        console.log(`property ${name} does not exist on object`)
    }
  }
}

© www.soinside.com 2019 - 2024. All rights reserved.