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?
2 Answers
+ 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!
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