What is the difference between saying “HTMLElement.prototype.someFunc =” and “HTMLElement.someFunc =”?

StackOverflow https://stackoverflow.com/questions/7216049

Question

I have, in many ocassions been able to register methods for all HTMLElements in both ways.
So I am curious, is there any difference?
Should I prefer one method over the other one?
What would be the right way to do it?

Was it helpful?

Solution

using prototype is making the function available to all objects in the prototype chain. Its basically extending the class. While other one is just adding a property to the current element. But as Felix suggest the right thing would be not to do this at all.

OTHER TIPS

Because JavaScript is a prototype based language and not a Class based language they keyword .prototype.variable or .__proto__.variable (for Math) is used to directly access the prototype (Like the Class Definition in classed based languages) and modify it effecting ALL of its instances even if the instances has been created before the prototype is modified. Whereas .variable without accessing the prototype only affects the specified instance.

In short "HTMLElement.prototype.someFunc =" will allow ALL HTMLElements (and prototypes which inherit from HTMLElement" to access someFunc. And HTMLElement.someFunc should only be used to allow a specific instance of HTMLELement access to someFunc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top