开发者

Javascript: Is it possible to memoize a getter by writing a value property to a derived object?

Just an idea I had but I cannot get it to work. Simply setting the property "this.length = len" throws an error because there is no setter. Setting the length property descriptor "configurable: true" causes the prototype property to change along with the instance. In this case x and y are undefined in the prototype so length becomes NaN instead of staying a getter like I want. If configurable is false then:

Chromium: Length is set on the derived object. the getter still works on the prototype but it appears as an error value.

FF4: Changes to the getter are silently rejected and length is not set on the deri开发者_开发百科ved object.

Here's what I have so far.

function Vec2(x, y) {
  this.x = x;
  this.y = y;
}
Vec2.prototype = Object.create(
  Object.prototype,
  {
    length: {
      get: function length (vec) {
         var len = Math.sqrt(this.x * this.x + this.y * this.y);
         Object.defineProperty(this, 'length', {value: len});
         return len;
      },
      configurable: true
    }
  }
);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜