+ 2

Syntax question

function person(name, age) { this.name= name; this.age = age; this.yearOfBirth = bornYear; //or bornYear(); } function bornYear() { return 2016 - this.age; } Which one is correct or both possible?

21st Jun 2017, 3:35 PM
Upside
Upside - avatar
6 Answers
+ 3
You may need to send the age to the function you're calling. Depends upon the scope of your variable.
21st Jun 2017, 3:53 PM
AgentSmith
+ 3
Worth noting, in Javascript you can assign functions to a variable and you can call functions immediately. this.yearOfBirth = bornYear; ^This assigns the function to the variable, but it does not execute it yet, necessarily. this.yearOfBirth = bornYear(this.age); ^This will execute the function immediately and assign the variable the returned value. In which case, I would feed it the age variable to ensure the function can access its value. Also, it's worth mentioning that we're in 2017. :)
21st Jun 2017, 4:09 PM
AgentSmith
+ 2
functions are objects so if you omit the parenthesis you're assigning the variable yearOfBirth to the function. In this case it might give the same result. More info on this here: https://stackoverflow.com/questions/3246928/in-javascript-does-it-make-a-difference-if-i-call-a-function-with-parentheses
21st Jun 2017, 4:00 PM
Rrestoring faith
Rrestoring faith - avatar
+ 1
sure? because in the tutorial some examples are like the first option. i was just thinking the same as you. actually i want to understand why it can be written without parenthesis and still execute the function. my thought was that maybe if a variable has no value its constructor is executed?!
21st Jun 2017, 3:53 PM
Upside
Upside - avatar
0
ok got it. thx alot
21st Jun 2017, 4:04 PM
Upside
Upside - avatar
0
Do you mean by that nowadays its not used anymore in that way? I learned programming 10 years ago and sadly stopped then.. now i want to program some shop and i use this to get knowledge and some open source codes. Actually going good but if you have tips where to find newer knowledge i would appreciate it.
21st Jun 2017, 4:10 PM
Upside
Upside - avatar