0

JavaScript - Are METHODS always within constructors?

With a bit of Java background, I find JavaScript a bit strange when it comes to methods. Are JavaScript methods always within constructors?

26th Apr 2022, 4:57 AM
Solus
Solus - avatar
2 odpowiedzi
+ 1
Compare the below two snippets of code: ============================================ function person(name, age) { this.name = name; this.age = age; this.changeName = function (name) { this.name = name; } } ============================================ function person(name, age) { this.name= name; this.age = age; this.yearOfBirth = bornYear; // () not required } function bornYear() { return 2022 - this.age; } ============================================ The method name should be in the constructor. The function that gets assigned to this method name can be outside the constructor. This function technically IS the method. ============================================ Call the method by the property name you specified in the constructor function, rather than the function name. var p = new person("Solus", 99); document.write(p.yearOfBirth()); // () needed!
26th Apr 2022, 5:25 AM
Solus
Solus - avatar
0
Solus good job👍 but what was your motive behind all this🤔🤔 we already know this🤘👌 for 2nd case yes function definition can be outside the constructor but in that case we need to provide reference to that fumction from inside the constructor, like you did or just do it like 1st case, just define the function/method inside the constructor
26th Apr 2022, 6:08 AM
NonStop CODING
NonStop CODING - avatar