[英]can't access this.table property in javascript class
我在 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
是未定義的? 我錯過了什么? 我將不勝感激任何幫助!
因為你第一次調用是創建(超級)並且只有在你設置 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();
我會從 UsersModel 構造函數中刪除 table 參數,因為你沒有傳入它。它也不應該改變,表名通常不是動態的。 這是我將其更改為:
class UsersModel extends Model {
constructor(options) {
super(options, "users")
}
}
我還選擇不將 options 參數設為可選(非雙關語)。 我什至建議將用戶名和郵件作為單獨的參數,然后將它們作為對象傳遞給基本模型構造函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.