0
JavaScript Method parenthesis
Why does document.write(p.yearOfBirth()); work only with parenthesis after yearOfBirth??
5 Réponses
0
Because the p.yearOfBirth is a method. And not just in JavaScript but in all languages, parentheses are used to call/execute functions. Like print(), log() etc.
0
Okay, thank you. I was confused because when we want to print the changed Name or Age or whatever and we use the method changeName or changeAge and in document.write we don't call it using "p.changeName" or "p.changeAge". Rather we write document.write(p.name); without using methodName and parenthesis.
0
Yes because they are attributes. Attributes are variables which are present inside an object. And methods are functions present inside an object. Just like you don't need parentheses to access variables, you don't need them for attributes to. For example,
let obj = {
name : "XXX",
age : 100,
sayHello : function(){
document.write( "I said hello" )
}
}
Now name and age are attributes. You can access them by doing
obj.name
obj.age
But add is a function, and you need parentheses to call it.
sayHello()
0
attribute / property have quite same meanings (and are often missused), but in JS and all the more in web context, common usage is to talk about object properties rather than attributes (wich in web context, are related to the inlined attribute of the element tags)...
Anyway, in JS global variables under the hood are properties of the global object (window in browsers context)... and always under the hood, properties of any object is implemented less or more with getter and setter (i.e.: hidden function, wich are called).
So, you may see properties as shorthand for implicit function call (with none or once argument, in regard to the operation: read or write -- assign -- value).
... And you could define your customs properties with getter and/or setter (implicitly or explicitly) thanks to Object.defineProperty() and defineProperties() ;)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
(Object.create also allows defining custom properties)
0
Thank you for your informative answers 🙂