[removed] How to add getter to an existing object

前端 未结 5 1456
说谎
说谎 2020-12-09 14:35

I can have a getter in a JavaScript object like this:

var member = {
    firstName:"XYZ", 
    lastName:"zzz", 
    get fullName(){ return         


        
相关标签:
5条回答
  • 2020-12-09 14:53

    Moreover, you can add a custom getter and preserve the old value if it is not supposed to be calculated from other values, like in your example. To do so, create additional context layer using an anonimous function like this:

    (function(){
        var oldValue = yourObject[targetProperty];
        var currentValue = oldValue;
        var getter = function() {
            return currentValue; // or do something before returning, like applying parseInt or whatever
        };
        var setter = function(newValue) {
            currentValue = newValue; // or add some customization as well
        };
        Object.defineProperty(yourObject,targetProperty,{
            get: getter,
            set: setter,
            enumerable: true, // depending on your needs
            configurable: true // depending on your needs
        });
    })();
    
    0 讨论(0)
  • 2020-12-09 14:56

    You can use the new Object.defineProperty this way:

    Object.defineProperty(
        member, 
        'prop', 
        {
            get: function() { 
                return this.lastName.toUpperCase()
            }
        }
    );
    

    In the past you had to use __defineGetter__ but now it has been deprecated.

    0 讨论(0)
  • 2020-12-09 15:11

    You can only use get and set in a Class, It's mean that getter and setter method. but you can add a function to class:

    member.isGuest = function isGuest(){ return this.firstName=='Guest';}
    
    member.isGuest()
    

    the get means that property can be read! the set means that property can be write! You can look it in book 《JavaScript:The.Definitive.Guide》6edition the 6 chapter!

    0 讨论(0)
  • 2020-12-09 15:12

    This is possible not only with the above solutions, but also using the ... operator.

    // Initialize x
    var x = {
      x: 5
    }
    
    // Log x.x and x.y
    console.log(x.x, x.y /* undefined */)
    
    x = {
      ...x, // {...x} is the same as {x: x.x}
      
      // The getter
      get y() {
        return this.x
      }
    }
    
    // Log x.x and x.y
    console.log(x.x, x.y /* Not undefined */)
    
    // Set x.x to 1234
    x.x = 1234
    
    // Log x.x and x.y
    console.log(x.x, x.y)

    ... is the spread operator, which "spreads" the contents of the object it is used on, hence the name. For example:

    • doSomething(...[1, 2, 3]) is the same as doSomething(1, 2, 3)
    • { ...{x: 1, y: 2, z: 3} } is the same as { x: 1, y: 2, z: 3 }
    0 讨论(0)
  • 2020-12-09 15:15

    try defineProperty

    Object.defineProperty(member, 'isGuest', {
      get: function() { return this.firstName=='Guest' }
    });
    
    0 讨论(0)
提交回复
热议问题