javascript - Performance wise which is better: An object protype or an constructors native function? -


performance wise better practice: create prototype or add methood contructor.

this code:

function dategreeting(selector) {     this.element = document.queryselectorall(selector)[0];     this.date = new date();     this.hours = this.date.gethours();     this.greeting = function () {         if(this.hours <= 11) {             return "morning";         } else if (this.hours >= 12 && this.hours <= 17) {             return "afternoon";         } else {             return "evening";         }     } } dategreeting.prototype.append = function () {     this.element.innerhtml = this.greeting(); } 

i turn this.greeting prototype, increased performance or decrease it? (or nothing..)

should put methods in prototype or in constructor?

when creating many objects of type dategreeting of them have copy of methods have defined on constructor.
while working objects changing properties, methods remain same.
declaring methods on prototype more resource-saving approach. therefore, can work many objects share same methods without copying methods each instance.
declaring methods on custom prototype better performance:

// method shared dategreeting instances dategreeting.prototype.greeting = function () {     if(this.hours <= 11) {         return "morning";     } else if (this.hours >= 12 && this.hours <= 17) {         return "afternoon";     } else {         return "evening";     } }  var greeting1 = new dategreeting(".greet"); var greeting2 = new dategreeting(".greet"); console.log(greeting1, greeting2); // output: 

output

while adding methods constructor creates copy of each method on each object instance:

function dategreeting(selector) {     ...     this.greeting = function () {         if(this.hours <= 11) {             return "morning";         } else if (this.hours >= 12 && this.hours <= 17) {             return "afternoon";         } else {             return "evening";         }     } }  var greeting1 = new dategreeting(".greet"); var greeting2 = new dategreeting(".greet"); console.log(greeting1, greeting2); // output: 

output2


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -