My knowledge of words might not be sufficient to find this by myself the explanation on the www. So please excuse me if this might be a duplicate.
I'm currently trying to figure out why we use "this" in a function constructor instead of simply returning an object?
E.g. this JSFiddle
// Using this inside function
function Student1(first,last) {
this.firstName = first;
this.lastName = last;
this.display = function(){
return this.firstName + " " + this.lastName;
};
}
const harry = new Student1("Harry", "Potter");
document.querySelector("div").innerHTML = harry.display();
document.querySelector("div").innerHTML += "<br>";
// Returning object
function Studen2(first,last){
return {
firstName: first,
lastName: last,
display(){
return this.firstName + " " + this.lastName;
}
};
}
const ron = new Student1("Ron", "Weasley");
document.querySelector("div").innerHTML += ron.display();
Anyone mind to explain or guide me to the right direction?
Generally you will want to define the object methods on the class prototype, so that they don't have to be reinstantiated every time you create a new instance of the class, e.g.:
function Student1(first,last) {
this.firstName = first;
this.lastName = last;
}
Student1.prototype.display = function() {
return this.firstName + " " + this.lastName;
}
const harry = new Student1("Harry", "Potter");
document.querySelector("div").innerHTML = harry.display();
If you just return an (anonymous) object, it won't have a prototype and you'll have to define the function every time the construction function gets called.
Also, in your example:
harry instanceof Student1 // true
ron instanceof Student2 // false
So you can't use instanceof.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments