在JavaScript中装饰实例方法的问题

时间:2016-01-28 22:17:28

标签: javascript ecmascript-next

我在ES6中装饰实例方法遇到了一个难题。我在装饰方法时没有任何问题,但似乎它仍然坚持使用类的实例的单个状态。以下是我正在处理的内容:

class Test {
    init() {
        this.foo = 'bar';
    }

    @decorator
    decoratedMethod() {
        console.log(this.foo); // undefined
    }
}

let test = new Test();
test.init();
test.decoratedMethod();

function decorator(target, name, descriptor) {
     let fn = target[ name ].bind(target, 'a', 'b');
     return fn;
}

我意识到上面的代码正是应该做的,但是如果我想访问foo并且其他属性添加到范围,我该如何装饰decoratedMethod并仍然绑定新的功能属性?

1 个答案:

答案 0 :(得分:3)

方法装饰器在类声明时运行一次,而不是在实例化类时运行。这意味着您示例中的targetTest.prototype,而不是实例。所以你的例子基本上是:

class Test {
  init() {
    this.foo = 'bar';
  }

  decoratedMethod() {
    console.log(this.foo); // undefined
  }
}

Test.prototype.decoratedMethod = 
    Test.prototype.decoratedMethod.bind(Test.prototype, 'a', 'b');

这应该清楚你的代码失败的原因。您绑定的对象没有foo属性,只有实例。

如果您希望为每个实例处理装饰器,事情会变得更复杂,并且您需要在创建实例后进行绑定。一种方法是

function decorator(target, name, descriptor){
  const {value} = descriptor;
  delete descriptor.value;
  delete descriptor.writable;
  descriptor.get = function(){
    // Create an instance of the bound function for the instance.
    // And set an instance property to override the property
    // from the object prototype.
    Object.defineProperty(this, name, {
      enumerable: descriptor.enumerable,
      configurable: descriptor.configurable,
      value: value.bind(this, 'a', 'b'),
    });

    return this[name];
  };
}
相关问题