是否是修改JavaScript内置原型的反模式? [英] Is it an anti-pattern to modify JavaScript's built-in prototypes?

查看:97
本文介绍了是否是修改JavaScript内置原型的反模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从这篇文章了解到,这是一种反模式在JavaScript中修改 Object 的原型。我很好奇,但是,如果它被广泛认为是一个反模式来修改其他内置原型。

I understand from this post, that it's an anti-pattern to modify Object's prototype in JavaScript. I was curious, however, if it's widely considered to be an antipattern to modify other 'built-in' prototypes.

例如:假设我们要将 setPixel(x,y,color)函数添加到 CanvasRenderingContext2D - 抽象出获取上下文图像数据的义务,将像素设置为某种颜色,并将图像数据返回。

For example: say we wanted to add a setPixel(x,y,color) function to CanvasRenderingContext2D - to abstract out the duty of getting the context's image data, setting a pixel to a certain color, and putting the image data back.

CanvasRenderingContext2D.prototype.setPixel = function(x, y, color){
    var imgdata = this.createImageData(1,1);
    imgdata.data[0] = color.r;
    imgdata.data[1] = color.g;
    imgdata.data[2] = color.b;
    imgdata.data[3] = color.a;
    this.putImageData(imgdata,x,y);
};



我没有测试这个代码,但你得到的想法。

I haven't tested this code, but you get the idea. Is something like this against 'best practices' ?

推荐答案

一般来说,如果你在一个基本对象中添加一个原型JavaScript,你应该有一个很好的理由,并且真的没有理由修改Object,因为你不知道如何预测最终结果将是什么修改。

Generally, if you are adding a prototype to one of the base objects in JavaScript, you should have a good reason, and there is really no reason to modify Object, since you don't know how to predict what the end result will be of that modification.

我倾向于添加startsWith,trim和一些其他函数到String,例如,因为这些是帮助函数,就像向Firefox添加一些函数,而不是IE存在的Array是有意义的(例如过滤函数) 。

I tend to add startsWith, trim and some other functions to String, for example, as these are helper functions, just as adding some functions to Array that exists for Firefox but not IE just makes sense (such as the filter function).

所以,添加到Canvas是好的,但如果有人正在使用你的库,并使用excanvas。它会导致一个问题吗?

So, adding to the Canvas is fine, but, what if someone is using your library, and using excanvas. Will it cause a problem?

你可能想要探索,或者证明它不工作excanvas,如果你有一个小测试,以显示

You either may want to explore that, or document that it doesn't work for excanvas, and if you have a small test to show that, please include it, so that if later there is a new version, and your problem disappears people can verify that.

UPDATE: $ b。如果您的问题已消失, $ b你将要这样做:

UPDATE: You will want to do this:

if (!CanvasRenderingContext2D.setPixel) {
...
}

这样,如果有人用这个名字包含了一个,你不会覆盖它,您需要妥善处理。

That way, if someone did include one by that name you will not overwrite it, but you will need to handle it gracefully.

这篇关于是否是修改JavaScript内置原型的反模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆