0

for example, here is a snippet of code

let myQuestion = {
  _greeting: 'Hello',
  
  sayHello() {
    console.log(this._greeting);
  },
  
  get sayHelloWithGet() {
    console.log(this._greeting);
  }
};

myQuestion.sayHello();
myQuestion.sayHelloWithGet;

Both of them did the same thing, both of them are called method, but why different usage?

imtk
  • 373
  • 3
  • 11

1 Answers1

2

...both of them are called method...

Not usually. Usually getters and setters are called getters and setters, or collectively "accessors" (but yes, sometimes "accessor methods").

...but why different usage?

Because that's the point: Sometimes you want those different semantics at point of use, something that looks like a simple property access even though it runs a function under the covers. Methods are verbs, non-method properties are nouns.

(Of course, when disguising a function call as a property access, it's incumbent upon the programmer to ensure that the cost of reading the property is low.)


Vaguely related: Properties with accessors are also included in various serializations, whereas properties referencing functions typically aren't. Example:

var o = {
  get foo() {
    return 42;
  },
  bar() {
    return 67;
  }
};
console.log(JSON.stringify(o));
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    ok, I did not know what is "accessor method" before, Thank you so much ^^ – imtk Sep 27 '17 at 11:01
  • @DonghuiMa: Glad that helped. FWIW, in some languages without this special property behavior, an "accessor method" would be an actual method. For instance, in Java, you'd have `getWhatever` and `setWhatever` as actual methods. But in JavaScript, C#, and a few others, they can be actual properties with hidden function calls. – T.J. Crowder Sep 27 '17 at 11:02
  • once again ^^ thank you for telling me this, though it is a bit of hard for me to understand. – imtk Sep 27 '17 at 11:05