开发者

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

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?

开发者_如何学Go What would be the right way to do it?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜