4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptで非推奨プロパティを示す

Posted at

プロパティの名前変えたから今後は新しい方を使って欲しい。でも古いプロパティにアクセスしているコードがあるからそことの互換性は保ちたい。
みたいなときに使える良い例が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.separationeffect.targetDistance にアクセスするとコンソールに警告が出るので、使う側から非推奨プロパティだということがわかる。
effect.separationeffect.targetDistance は実際にはそれぞれ effect.eyeSeparationeffect.focalLength に値を格納しているため、変数の領域は一つで済んでいる。

Object.definePropertiesについては良いまとめがあったので一読すべし。
http://constellation.hatenablog.com/entry/20101205/1291564928

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?