[removed] How to add getter to an existing object

前端 未结 5 1477
说谎
说谎 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 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 }

提交回复
热议问题