NodeJS类始终返回未定义

问题描述 投票:0回答:2

我正在尝试将值从一个类传递到另一个js文件,但是在所有尝试中,它总是使我返回未定义的值。这是我的舞台

config.js

class Token {
  _token = '';

  constructor(token) {
    this._token = token;
  }

  get getToken() {
    return this._token;
  }
}

class Url {
  get getUrl() {
    return 'https://api.com';
  }
}

exports.token = Token;
exports.url = Url;

instance.js

const config = require('./config');

let tkn = new config.token();
console.log('tkn', tkn.getToken);
console.log('TKN', config.token.getToken);

let url = new config.url();
console.log('URL', config.url.getUrl);
console.log('url', tkn.getUrl);
javascript node.js class instance
2个回答
0
投票

您的脚本的正确用法将是

const config = require('./config');

let tkn = new config.token('value');
//                         ^^^^^^^^
console.log('tkn', tkn.getToken); // value

let url = new config.url();
console.log('url', url.getUrl); // https://api.com
//                 ^^^

您定义的getter属性不是静态的,无法在config.tokenconfig.url上访问它们。


0
投票

我在这里评论了问题:

const config = require('./config');

let tkn = new config.token(); // Token constructor expects an argument.
console.log('tkn', tkn.getToken); // This is correct and will work provided the constructor argument.
console.log('TKN', config.token.getToken); // You must instantiate the token and use the instance.

let url = new config.url();
console.log('URL', config.url.getUrl); // Same as with the token. It must be instantiated and getUrl accessed through that instance.
console.log('url', tkn.getUrl); // Here you're trying to call getUrl of the Token class but it doesn't exist.

固定版本

const config = require('./config');

let tkn = new config.token("token");
console.log('tkn', tkn.getToken);

let url = new config.url();
console.log('URL', url.getUrl);
© www.soinside.com 2019 - 2024. All rights reserved.