第一次使用后移除该功能
Remove the function after it being used for the first time
我有一个简单的 SQL 查询生成器,如下所示:
class QueryBuilder {
select(fields) {
this.query = "SELECT `" + fields.join("`, `") + "` ";
return this;
}
from(table) {
this.query += "FROM `" + table + "` ";
return this;
}
}
问题是它 returns this
所以我可以这样做:
const sql = builder.select("field1", "field2").from("table").select("I shouldn't be able to call select");
有什么方法可以 disable/remove 来自 Builder
实例的 select
函数并在第一次调用后自动完成吗?或者强调第二次调用该函数将导致错误。
解法:
根据@Sohail 的回答,要使其像那样工作,您只需要将 from()
从 QueryBuilder
class 移动到 return 作为一个字段将查询作为新的普通对象:
class QueryBuilder {
static select(fields) {
this.query = "SELECT `" + fields.join("`, `") + "` ";
return {
query: this.query,
from
};
}
}
function from(table) {
this.query += "FROM `" + table + "` ";
return {
query: this.query,
where: function() {}
};
}
您可以 return 特定的 method
而不是 this
,它可以在此方法之后在链中调用。
示例:
class QueryBuilder {
select(fields) {
this.query = "SELECT `" + fields.join("`, `") + "` ";
return {
from: this.from.bind(this)
};
}
from(table) {
this.query += "FROM `" + table + "` ";
return {
where : ""
};
}
}
您可以尝试以下修改:
select(fields) {
if(!this.query.includes("SELECT")){
this.query = "SELECT `" + fields.join("`, `") + "` ";
}
return this;
}
我有一个简单的 SQL 查询生成器,如下所示:
class QueryBuilder {
select(fields) {
this.query = "SELECT `" + fields.join("`, `") + "` ";
return this;
}
from(table) {
this.query += "FROM `" + table + "` ";
return this;
}
}
问题是它 returns this
所以我可以这样做:
const sql = builder.select("field1", "field2").from("table").select("I shouldn't be able to call select");
有什么方法可以 disable/remove 来自 Builder
实例的 select
函数并在第一次调用后自动完成吗?或者强调第二次调用该函数将导致错误。
解法:
根据@Sohail 的回答,要使其像那样工作,您只需要将 from()
从 QueryBuilder
class 移动到 return 作为一个字段将查询作为新的普通对象:
class QueryBuilder {
static select(fields) {
this.query = "SELECT `" + fields.join("`, `") + "` ";
return {
query: this.query,
from
};
}
}
function from(table) {
this.query += "FROM `" + table + "` ";
return {
query: this.query,
where: function() {}
};
}
您可以 return 特定的 method
而不是 this
,它可以在此方法之后在链中调用。
示例:
class QueryBuilder {
select(fields) {
this.query = "SELECT `" + fields.join("`, `") + "` ";
return {
from: this.from.bind(this)
};
}
from(table) {
this.query += "FROM `" + table + "` ";
return {
where : ""
};
}
}
您可以尝试以下修改:
select(fields) {
if(!this.query.includes("SELECT")){
this.query = "SELECT `" + fields.join("`, `") + "` ";
}
return this;
}