在构造函数

时间:2016-07-11 17:55:57

标签: javascript node.js ecmascript-6

我正在开发一个数据库管理器,它可以根据某些运行时参数与任何数据库一起使用。我当前的设置有一些工厂根据函数的strategy参数创建不同的类。例如:

module.exports = function ConnectionFactory(proxyStrategy) {
  // proxyStrategy.connection === ProxyConnectionStrategy
  class ProxyConnection extends proxyStrategy.connection {
    constructor(...args){ super(...args) }
  }
  ProxyConnection.prototype.dbManager = strategy.dbManager;
  return ProxyConnection;
}

strategy.connection类定义构造期间的某些行为,即使用dbManager属性。我能够通过Object.getOwnPropertyNames(this.__proto__)看到它,我甚至可以将其分配给变量(const dbManager = this.__proto__.dbManager),但我尝试将其分配给this或致电它上面的任何功能我奇怪地失去了它的访问权限。以下是这种疯狂行为的一个例子:

class ConnectionTemplate {
  constructor(URI, dbName, username, password) {
    this.URI = URI;
    this.dbName = dbName;
  }    
  open() {}
  close() {}  
}

class ProxyConnectionStrategy extends ConnectionTemplate {
  constructor(URI='mongodb://localhost:27017', dbName='proxyDb-test') {
    super(URI, dbName)
    console.log('Proxy Dunder', Object.getOwnPropertyNames(this.__proto__))
    const dbManager = this.__proto__.dbManager;
    const dbConnection = dbManager.createConnection(this.URI)
    // this.dbConnection = dbConnection;
}
//console.log -> Proxy Dunder [ 'constructor', 'dbManager' ] 
console.log('Proxy Dunder', Object.getOwnPropertyNames(this.__proto__))
const dbManager = this.__proto__.dbManager;
const dbConnection = dbManager.createConnection(this.URI)
this.dbConnection = dbConnection;

//console.log -> Proxy Dunder [ 'constructor', 'open', 'close' ]

只需添加一个额外的行,将属性分配给this就足以完全失去对该属性的访问权,就好像编译器在这两种情况下以某种方式“完成”构造一样。有什么想法吗?

0 个答案:

没有答案