プロパティの名前変えたから今後は新しい方を使って欲しい。でも古いプロパティにアクセスしているコードがあるからそことの互換性は保ちたい。
みたいなときに使える良い例がthree.jsのコードで見つけたので紹介。
THREE.StereoEffect = function(renderer) {
// API
var scope = this;
this.eyeSeparation = 3;
this.focalLength = 15; // Distance to the non-parallax or projection plane
Object.defineProperties(this, {
separation: {
get: function() {
return scope.eyeSeparation;
},
set: function(value) {
console.warn('THREE.StereoEffect: .separation is now .eyeSeparation.');
scope.eyeSeparation = value;
}
},
targetDistance: {
get: function() {
return scope.focalLength;
},
set: function(value) {
console.warn('THREE.StereoEffect: .targetDistance is now .focalLength.');
scope.focalLength = value;
}
}
});
// ...以下略
利用するときには
var effect = new THREE.StereoEffect(renderer);
このとき effect
のプロパティを読み取ると
console.log( effect.eyeSeparation ); // => 3
console.log( effect.focalLength); // => 15
console.log( effect.separation); // => 3 (THREE.StereoEffect: .separation is now .eyeSeparation.)
console.log( effect.targetDistance); // => 15 (THREE.StereoEffect: .targetDistance is now .focalLength.)
effect.separation
と effect.targetDistance
にアクセスするとコンソールに警告が出るので、使う側から非推奨プロパティだということがわかる。
effect.separation
と effect.targetDistance
は実際にはそれぞれ effect.eyeSeparation
と effect.focalLength
に値を格納しているため、変数の領域は一つで済んでいる。
Object.definePropertiesについては良いまとめがあったので一読すべし。
http://constellation.hatenablog.com/entry/20101205/1291564928