我有一个这样的构造函数:
function IDBCrud(table: string): void {
...
}
IDBCrud.prototype.get = function(...) { ... }
IDBCrud.prototype.post = function(...) { ... }
它像这样使用:
const accounts = new IDBCrud('Accounts');
accounts.get( ... );
accounts.create( ... );
但有时,我想用与属性相同的名称直接定义方法以对象,以便调用而不是原型的方法。
// Override get method for some reason
accounts.get = function( ... ) {
// Do some stuffs...
...
// Now call prototype get
return this.__proto__.get.apply(this, arguments);
}
但是当我运行流时,它失败了:
16: accounts.get = function(match, options) {
^^^ property `get`. Property not found in
16: accounts.get = function(match, options) {
^^^^^^^^^^^^ new object
因为 IDBCrud 没有"get"属性(或方法(。但是如果我只是像这样用空值编写它们:
function IDBCrud(...): ... {
this.get = function() {};
this.create = function() {};
...
}
如果在这种情况下应该工作,但如果这样做,我必须重新定义每个"get"方法来调用原型的 get 方法。
const accounts = new IDBCrud('accounts');
accounts.get = function() { ... }; // Override
accounts.get(); // works
const users = new IDBCrud('users');
users.get(); // Invokes users.get and it's empty function, instead of prototype.get
我不想每次制作 IDBCrud 实例时都这样做,我只想只覆盖它所需要的。
没有流动,这不是问题,但有了它,它就会失败。
那么,如何通过流量实现这一目标呢?任何建议将不胜感激。
仅在要实现不同行为的对象实例上覆盖它:
function IDBCrud(table){
}
IDBCrud.prototype.get = function() { console.log('get1'); }
var a = new IDBCrud();
a.get(); // get1
a.get = function() { console.log('get2'); }
a.get(); // get2
var b = new IDBCrud();
b.get(); // get1
Flow 是为支持 es6 类而故意构建的,出于安全原因,它阻止我在运行时添加方法。
解决方案很简单,将构造函数转换为类并创建扩展 IDBCrud 和覆盖方法的新类,它现在可以工作了。