【问题标题】:can't access this.table property in javascript class无法访问 javascript 类中的 this.table 属性
【发布时间】:2021-02-19 07:47:12
【问题描述】:

我在 js 中创建了一个类,它创建了一个这样的 MySQL 模型:

class Model {
  constructor(options = {}, table) {
    this.options = options;
    this.table = table;
    this.create();
  }
  create() {
    let queryString = `INSERT INTO ${this.table}`;
    let fieldsString = ``;
    let valuesString = ``;
    for (let prop in this.options) {
      fieldsString += `${prop},`;
      valuesString += `${this.options[prop]},`;
      //console.log(prop, this.options[prop]);
    }
    fieldsString = fieldsString.slice(0, -1);
    valuesString = valuesString.slice(0, -1);
    queryString = `${queryString} (${fieldsString}) VALUES (${valuesString})`;
    console.log(queryString);
  }
}

class UsersModel extends Model {
  constructor(options = {}, table) {
    super(options, table);
    this.table = "users";
  }
}
const u1 = new UsersModel({
  username: "test",
  mail: "darya",
});

当我运行构造函数变量queryString 看起来像这样:INSERT INTO undefined (username, mail) VALUES (test, Darya) 为什么this.table 未定义?我错过了什么? 我将不胜感激!

【问题讨论】:

    标签: javascript mysql node.js oop


    【解决方案1】:

    因为您首先调用的是 create(在 super 中)并且只有在您设置 this.table 之后。

    class Model {
      constructor(table) {
        // table is undefined, call create..
        this.table = table;
        this.create();
      }
      create() {
        let queryString = `INSERT INTO ${this.table}`;
        console.log(queryString);
      }
    }
    
    class UsersModel extends Model {
      constructor(table) {
        // table is undefined, call super..
        super(table); 
        this.table = "users";
        // here you already have table name, so create works with it
        this.create(); 
      }
    }
    
    new UsersModel();

    【讨论】:

    • 我明白我错过了什么!感谢您的帮助!
    【解决方案2】:

    我会从 UsersModel 构造函数中删除 table 参数,因为您没有将它传入。它也不应该更改,表名通常不是动态的。这是我将其更改为:

    class UsersModel extends Model {
      constructor(options) {
        super(options, "users")
      }
    }
    

    我还选择不将选项参数设为可选(双关语不是有意的)。我什至建议将用户名和邮件作为单独的参数,然后将它们作为对象传递给基础模型构造函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-12
      • 1970-01-01
      • 2014-11-21
      • 2018-09-13
      • 2016-02-11
      • 1970-01-01
      • 2019-08-24
      • 2015-08-02
      相关资源
      最近更新 更多