javascript 对象中的访问器和普通函数有什么区别?

What is the difference between accessors and normal functions in javascript object?

除了调用方式之外,javascript 对象中这两个函数(一个是访问器 属性 getter)之间的具体区别是什么?

var o = {
  foo: function() { return "bar"; },
  get foo2() { return "bar2"; }
}

From MDN, Sometimes it is desirable to allow access to a property that returns a dynamically computed value, or you may want to reflect the status of an internal variable without requiring the use of explicit method calls. In JavaScript, this can be accomplished with the use of a getter.


A method is a function associated with an object, or, simply put, a method is a property of an object that is a function. Methods are defined the way normal functions are defined, except that they have to be assigned as the property of an object.

foo2 比 will/can 保存动态值的方法更像 属性。

var o = {
  foo: function() {
    return "bar";
  },
  get foo2() {
    return "bar2";
  }
};
//To invoke 'foo'
console.log(o.foo());
//To invoke 'foo2'
console.log(o.foo2);