在JavaScript中,特别是NodeJS上的ES6,我可以直接在运行时操作类的getter和setter函数吗?

可以说我有一个类定义如下:

class MyClass { constructor(a, b) { this._a = a; this._b = b; } get a() { return this._a; } set a(val) { this._a = val; } add() { return this._a + this._b; } } 

我希望能够直接在运行时访问和操作getter和setter函数,以便将它们包含在其他debugging代码中。 使用“添加”function,我可以这样做:

 let oldAdd = MyClass.prototype.add; MyClass.prototype.add = function() { console.log('add called!'); let result = oldAdd.call(this); console.log('add result: ' + result); return result; } 

但是,我找不到以类似方式修改getter和setter函数的方法。

我努力了

 let propDef = Reflect.getOwnPropertyDescriptor(MyClass.prototype, 'a'); propDef.get = function() { // ... } 

但是这个改变实际上并没有得到应用。

有任何想法吗?

我也有兴趣知道是否有可能以相同的方式访问和修改构造函数。

是的,你可以通过重新configuration属性来完成。 这是一个例子(见注释):

 class MyClass { constructor(a, b) { this._a = a; this._b = b; } get a() { return this._a; } set a(val) { this._a = val; } add() { return this._a + this._b; } } // Use it before redefining const instance = new MyClass(1, 2); console.log(instance.a); // 1 instance.a = 2; console.log(instance.a); // 2 // Redefine the property const desc = Reflect.getOwnPropertyDescriptor(MyClass.prototype, "a"); const {get: originalGet, set: originalSet} = desc; desc.get = function() { const value = originalGet.call(this); console.log("Debugging 'get' here, a's value is " + value); return value; }; desc.set = function(newValue) { console.log("Debugging 'set' here, a's new value is " + newValue); originalSet.call(this, newValue); }; Object.defineProperty(MyClass.prototype, "a", desc); // Use it after redefining console.log(instance.a); // 2, after seeing console statement instance.a = 3; // Triggers another console statement console.log(instance.a); // 3 (w/ console statement)