首页 > 编程语言 > 详细

JavaScript Patterns 2.5 (Not) Augmenting Build-in Prototypes

时间:2014-05-22 02:21:31      阅读:337      评论:0      收藏:0      [点我收藏+]

Disadvantage

  1. Other developers using your code will probably expect the built-in JavaScript methods to work consistently and will not expect your additions.
  2. 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:

  1. 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.
  2. 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.
  3. 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...
     };
}

JavaScript Patterns 2.5 (Not) Augmenting Build-in Prototypes,布布扣,bubuko.com

JavaScript Patterns 2.5 (Not) Augmenting Build-in Prototypes

原文:http://www.cnblogs.com/haokaibo/p/Not-Augmenting-Build-in-Prototypes.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!