JavasScript prototype まわりの備忘録
JavaScript を記述している際に, 他言語ではこうすればできるが JavaScript では? となったいくつかのこと.
Object
や prototype
について詳細なことが良くわかっていなのでご教授いただければと思います.
継承(みたいなもの)
以下のコードでは, LocationMode
の関数が使用可能な DisplayLocation
, LO
を定義.
// LocationModel が undefined の場合, || 演算子の右側が代入される.
var LocationModel = LocationModel || (function(){
function LocationModel(x, y) {
this.x = x;
this.y = y;
}
return LocationModel;
}());
LocationModel.prototype.setX = function(x) {
this.x = x;
return this;
}
LocationModel.prototype.setY = function(y) {
this.y = y;
return this;
}
// 原点O
var LO = (function(){
function LO() {
LocationModel.call(this, 0, 0);
}
return LO;
}());
LO.prototype = Object.create(LocationModel.prototype);
// 表示位置
var DisplayLocation = DisplayLocation = (function(){
function DisplayLocation(x, y) {
LocationModel.call(this, x, y);
}
return DisplayLocation;
}());
DisplayLocation.prototype = Object.create(LocationModel.prototype);
プロパティの定義 Object.defineProperty
XMLHttpRequest.DONE
や FileReader.DONE
と同じようにオブジェクト(以下の場合LocationModel
)に対して, 新しいプロパティを定義する.
参考: Object.defineProperty() - JavaScript | MDN
構文
Object.defineProperty(obj, prop, descriptor)
例
var LocationModel = LocationModel || (function(){
function LocationModel(x, y) {
this.x = x;
this.y = y;
}
return LocationModel;
}());
Object.defineProperty(LocationModel, 'PROP', {
value: 256, // 設定する値
writable: false // 変更不可
});
一方 TypeScript では
TypeScript
で class を作り継承したコードを書き, tsc
を通し生成したコードが以下の通り.
幾多の状況に対応できる __extends
関数を作り, 新しいオブジェクトを生成する際に即時関数の引数(_super
)に継承元を与えている.
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
}
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var LocationModel = /** @class */ (function () {
function LocationModel(x, y) {
this.x = x;
this.y = y;
}
LocationModel.prototype.setX = function (x) {
this.x = x;
};
LocationModel.PROP = 256;
return LocationModel;
}());
var LO = /** @class */ (function (_super) {
__extends(LO, _super);
function LO() {
return _super.call(this, 0, 0) || this;
}
return LO;
}(LocationModel));