gpt4 book ai didi

javascript - 如何向 javascript 对象添加方法?

转载 作者:行者123 更新时间:2023-11-28 02:16:07 25 4
gpt4 key购买 nike

我有我的 js 构造函数:

Function myobj(){
This.type = "triangle";
}

如何向其添加方法,例如:

Triangle.mymethod();

最佳答案

您可以使用原型(prototype):

// The standard canvas object
function CanvasObj(canvas, x, y, w, h, fill){
this.x = x||0;
this.y = y||0;
this.w = w||0;
this.h = h||0;
this.objects = [];
this.ctx = context_for(canvas);
this.init(canvas, fill);
};

// Initial set-up of the canvas
CanvasObj.prototype.init = function(canvas, fill){
position_element(canvas, this.x, this.y);
resize_canvas(canvas, this.w, this.h);
draw_rect(this.ctx, 0, 0, this.w, this.h, fill);
};

关于javascript - 如何向 javascript 对象添加方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16372882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com