const student = {
// data property
firstName: 'Monica',
// accessor property(getter)
get getName() {
return this.firstName;
}
};
// accessing data property
console.log(student.firstName); // Monica
// accessing getter methods
console.log(student.getName); // Monica
// trying to access as a method
console.log(student.getName()); // error
I can't access the getName() method while using () 1st brackets. Why is the last line showing error?
CodePudding user response:
You're using a getter:
the
get
syntax binds an object property to a function that will be called when that property is looked up.
So what you have in your code is a getName
property (and, for consistency, it should be called name
) not a method.
It's the same of having:
Object.defineProperty(student, 'name', {
get() {
return this.firstName;
},
});
If you want to have the a method instead of a property, you should define it as such:
const student = {
// data property
firstName: 'Monica',
// method, not getter
getName() {
return this.firstName;
}
};
But since JS supports getter, you could just have as you wrote (just less confused code, removing the double "get get"):
const student = {
// data property
firstName: 'Monica',
// accessor property(getter)
get name() {
return this.firstName;
}
};
CodePudding user response:
The reason is because it is a getter.
Getters (not to be confused with the getter design pattern in other languages) allow a property to be dynamic and are NOT functions. They are properties that have dynamic behavior. In order to achieve this dynamic behavior the implementation of getters require you to define them as functions.
Getters were introduced to close a capability gap where it was impossible to implement something like .innerHTML
in javascript. Previously if you wanted a property that behaves like .innerHTML
(that is, its value is dynamic) you would need to write it in C/C and create your own javascript interpreter (alternatively you could write a NaCl plugin in C/C for Chrome or Firefox, however most browsers these days have deprecated NaCl after they've removed support for Flash so you can't do that anymore).
So TLDR: it's because that's how it works: getters are NOT functions. They are variables that happen to have side-effects.
CodePudding user response:
A getter binds an object property to a function[*]. So it isn't a function type by itself and can't be invoked as such.
However as a function is a valid type in javascript, you can make a getter return a function itself:
const student = {
// data property
firstName: 'Monica',
// accessor property(getter)
get getName() {
return function() {
return 'func result';
}
}
};
// accessing data property
console.log(student.firstName); // Monica
// accessing getter methods
console.log(student.getName); // Monica
// trying to access as a method
console.log(student.getName()); // error