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"; }
}
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.
There are two ways to access properties: dot notation and bracket notation.
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.
There are 3 ways of writing a function in JavaScript: Function Declaration. Function Expression. Arrow Function.
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 afunction
associated with anobject
, or, simply put, a method is a property of an object that is a function. Methods are defined the waynormal 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With