关于班级文件,我有几个问题。我有以下课程
class CouchController {
constructor(couchbase, config) {
// You may either pass couchbase and config as params, or import directly into the controller
this.cluster = new couchbase.Cluster(config.cluster);
this.cluster.authenticate(config.userid, config.password);
this.bucket = cluster.openBucket(config.bucket);
this.N1qlQuery = couchbase.N1qlQuery;
}
doSomeQuery(queryString, callback) {
this.bucket.manager().createPrimaryIndex(function() {
this.bucket.query(
this.N1qlQuery.fromString("SELECT * FROM bucketname WHERE $1 in interests LIMIT 1"),
[queryString],
callback(err, result)
)
});
}
}
我的问题是如何从类文件外部访问doSomeQuery函数?内部没有访问函数的问题,但是我需要能够从外部调用它。我尝试过这样的事情
const CouchController = require("../controllers/CouchController")(couchbase, config)
let newTest = new CouchController
这样做newTest永远不会公开doSomeQuery方法。
还有方法的局限性是什么?它可以仅仅是一个简单的,还是可以异步使用诺言等?
对于以下问题,您应该考虑2个主要问题。
require
。如果您希望获得技术详细信息,这是NodeJS导出文档。// common module default export
module.exports = class CouchController {
constructor(couchbase, config) {
// You may either pass couchbase and config as params, or import directly into the controller
this.cluster = new couchbase.Cluster(config.cluster);
this.cluster.authenticate(config.userid, config.password);
this.bucket = cluster.openBucket(config.bucket);
this.N1qlQuery = couchbase.N1qlQuery;
}
doSomeQuery(queryString, callback) {
this.bucket.manager().createPrimaryIndex(function() {
this.bucket.query(
this.N1qlQuery.fromString("SELECT * FROM bucketname WHERE $1 in interests LIMIT 1"),
[queryString],
callback(err, result)
)
});
}
}
const CouchController = require('../controllers/CouchController');
const newTest = new CouchController(couchbase, config);
// now you can access the function :)
newTest.doSomeQuery("query it up", () => {
// here is your callback
})
如果您使用的是ES6模块或打字稿,则可以导出类似...
export default class CouchController {
// ...
}
...并导入...
import CouchController from '../controllers/CouchController';
const newTest = new CouchController(couchbase, config);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句