簡體   English   中英

如何從類外部訪問類中的方法

[英]How can I access methods inside a class from outside of class

我有幾個關於類文件的問題。 我有以下課程

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方法。

還有一個方法的局限性是什么? 它只能是一個簡單的,還是可以異步並使用承諾等?

對於以下問題,您應該考慮兩件主要事項。

  1. 首先正確導出。 我不確定你是否打算將其刪除,但重要的是將該類出口作為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)
              )     
            });
          }
  }
  1. 類初始化稍微不正確。 你可以在這里看到關於這個的文檔。 您可以將需求和初始化更改為...
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);

您需要在導入后實例化該類

更改以下內容

const CouchController = require("../controllers/CouchController")(couchbase, config)
let newTest = new CouchController

const CouchController = require("../controllers/CouchController")
let newTest = new CouchController(couchbase, config)

你還需要像這樣導出你的類

export default class CouchController {

然后訪問這樣的方法

newTest.doSomeQuery(...)

我經過一些反復思考后發現,部分問題是由於某種原因,視覺工作室代碼沒有向我展示讓我失望的方法。 手動打字使它最終有用。

這是我的類,我實際上將配置和couchbase本身移動到類文件中,因此不再需要傳遞它。

const couchbase = require("couchbase")
const config = require("../config/config")

 class CouchController {
    constructor() {
        // 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 = this.cluster.openBucket(config.bucket);
        this.N1qlQuery = couchbase.N1qlQuery;
      }



            getDoc2(docID){
                return new Promise((resolve,reject)=>{
                  this.bucket.get(docID ,(err, result)=>{
                    if(err) return reject(err);
                    return resolve({docID,result});
                  });
                });
              }




      }

     module.exports = CouchController

以下是我現在如何調用我的類並連接到后端以獲取我的數據。

const CouchController = require("./controllers/CouchController")
let newTest = new CouchController


const test= async()=>{
    let { docID, result } = await newTest.getDoc2("grid_info::20b05192-79e9-4e9d-94c9-91a4fc0a2765")

    console.log(docID)
    console.log(result)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM