JavaScript クラス/オブジェクトにコンストラクターはありますか? どのように作成されますか?
ベストアンサー1
プロトタイプの使用:
function Box(color) // Constructor
{
this.color = color;
}
Box.prototype.getColor = function()
{
return this.color;
};
「色」を非表示にする (プライベート メンバー変数に似ています):
function Box(col)
{
var color = col;
this.getColor = function()
{
return color;
};
}
使用法:
var blueBox = new Box("blue");
alert(blueBox.getColor()); // will alert blue
var greenBox = new Box("green");
alert(greenBox.getColor()); // will alert green