首页 > 代码库 > JavaScript Patterns 2.5 (Not) Augmenting Build-in Prototypes
JavaScript Patterns 2.5 (Not) Augmenting Build-in Prototypes
Disadvantage
- Other developers using your code will probably expect the built-in JavaScript methods to work consistently and will not expect your additions.
- Properties you add to the prototype may show up in loops that don‘t use hasOwnProperty(), so they can create confusion.
Augment build-in prototypes under all of the conditions below:
- It‘s expected that future ECMAScript versions or JavaScript implementations will implement this functionality as a built-in method consistently. For example, you can add methods described in ECMAScript 5 while waiting for the browsers to catch up. In this case you‘re just defining the useful methods ahead of time.
- You check if your custom property or method doesn‘t exist already—maybe already implemented somewhere else in the code or already part of the JavaScript engine of one of the browsers you support.
- You clearly document and communicate the change with the team.
If these three conditions are met, you can proceed with the custom addition to the prototype, following this pattern:
if (typeof Object.protoype.myMethod !== "function") { Object.protoype.myMethod = function () { // implementation... }; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。