[英]How to put a class method in a variable (javascript)
I have an instance of mysql connection named db.我有一个名为 db 的 mysql 连接实例。 db has a method named query to execute sql statement
db 有一个名为 query 的方法来执行 sql 语句
example例子
db.query('SELECT * FROM user',[], callback)
To avoid repeating db.query I would like to do something like为了避免重复 db.query 我想做类似的事情
const sqlCmd=db.query
sqlCmd('SELECT * FROM user',[], callback)
thanks in advance提前致谢
You have to bind the call to the db object:您必须将调用绑定到 db object:
const sqlCmd=db.query.bind(db)
You can use the new Function()
syntax, it's rarely used though:您可以使用
new Function()
语法,但它很少使用:
const queryDB = new Function(`db.query('SELECT * FROM user',[], callback)`)
//then you can call it as:
queryDB()
you can also pass pass arguments as new Function(['argA', 'argB'], "function body")
您还可以将 arguments 作为
new Function(['argA', 'argB'], "function body")
Remember, [[Environment]]
is set to reference not the current Lexical Environment, but the global one.请记住,
[[Environment]]
设置为引用的不是当前的词法环境,而是全局环境。
what you are trying to do here is called abstraction.您在这里尝试做的事情称为抽象。 Meaning you are adding a layer over the db class.
这意味着您要在 db class 上添加一个层。 So the simplest solution would be to create a module, add a method called query.
所以最简单的解决方案是创建一个模块,添加一个名为查询的方法。
// let db = 'your sql db instance'
module.export.sqlCmd = db.query;
import this like像这样导入
let sqlCmd = require('path to the above code')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.