Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

What is the specific difference between these two functions (one is an accessor property getter) in a javascript object other than the manner in which they are called?

var o = {
  foo: function() { return "bar"; },
  get foo2() { return "bar2"; }
}
like image 791
alex Avatar asked Jun 23 '16 05:06

alex


People also ask

What are JavaScript object accessors?

JavaScript object accessors are used to access and update the objects and two keywords used for this function are getter and the other is the setter. JavaScript introduced getters and setters in ES5 in 2009.

What are the two types of notations does object property have?

There are two ways to access properties: dot notation and bracket notation.

What is difference between method and property in JavaScript?

Object in JavaScript is just key-value pairs stored in a Hash. The difference between b/w property and method is that - property is a value stored in the hash key, whereas method is a function stored in the hash key.

How many types of functions are there in JavaScript?

There are 3 ways of writing a function in JavaScript: Function Declaration. Function Expression. Arrow Function.


1 Answers

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 acts more like a property than a method which will/can hold a dynamic value.

var o = {
  foo: function() {
    return "bar";
  },
  get foo2() {
    return "bar2";
  }
};
//To invoke 'foo'
console.log(o.foo());
//To invoke 'foo2'
console.log(o.foo2);
like image 187
Rayon Avatar answered Oct 21 '22 22:10

Rayon