JavaScript get/set methods vs. standard methods

后端 未结 1 427
梦毁少年i
梦毁少年i 2020-12-13 21:20

Why does JavaScript have two different ways to get/set object properties?

Example:

//implementation 1
var obj1 = {
  \"x\":1,
  get number() {return          


        
1条回答
  •  再見小時候
    2020-12-13 21:29

    Unlike normal methods, using get and set lets you operate on the object's properties directly (=== cleaner/lesser code) - while actually invoking the getter and setter methods behind-the-scenes.

    var obj1 = {
      "x":1,
      get number() {console.log('get was called'); return this.x},
      set number(n) {console.log('set was called'); this.x = n}
    };
    
    alert(obj1.number); // calls the getter (and prints to console)
    
    obj1.number = 10; // calls the setter (and prints to console)
    

    As the other answer mentioned, decide for/against using this depending on your target browser set.

    0 讨论(0)
提交回复
热议问题