Determine if a JavaScript property has a getter or setter defined?

前端 未结 5 2049
刺人心
刺人心 2020-12-01 09:58

Is it possible, given an object and property name to determine if that property is defined using either a getter or setter, or is it completely transparent? I only want to d

5条回答
  •  粉色の甜心
    2020-12-01 10:54

    Find the sample Object template for your java Script requirement:

    var Man=function(n,a){
      var name,age;
    
      function getName(){
           return this.name;
      }
    
      function getAge(){
           return this.age;
      }
      function create(){
           this.name=n;
           this.age=a;
           console.log('new object created');
      }
    
      function setAge(age){
           this.age=age;
      }
    
      function setName(name){
          this.name=name;
      }
      return{
       name:n,
       age:a,
       getName:getName,
       getAge:getAge,
       setName:setName,
       setAge:setAge
      };
    }
    
    var m1=new Man('Chaiguy',30);
    
    // To check if Property exist for an Object
    console.log(m1.hasOwnProperty('name'));
    
    // To get the name and age of the object
    
    console.log(m1.getName()+' is '+m1.getAge()+' years old.');
    

提交回复
热议问题