Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

canvas - Is it an anti-pattern to modify JavaScript's built-in prototypes?

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.

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' ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I wouldn't do it as it makes it hard to track what is implemented where. It also introduces the risk of two people overriding the same behavior.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...