javascript - Javascript将这个和其他参数传递给函数
问题描述
我有一个具有服务器对象的节点应用程序。这个对象有函数connect()。它应该返回一个布尔值并将连接存储在对象的 this 中。我可以得到骗局或这个。
未定义 this 的函数示例:
return this.mysql.createConnection({
host: this.env.host,
user: this.env.user,
password: this.env.password,
database: this.env.database
}).then( (function(con){
this.connection = con;
return con.state === 'authenticated';
}).apply(this, [con])).catch(function (err) {
console.log(err);
return false;
});
con 未定义的函数示例:
return this.mysql.createConnection({
host: this.env.host,
user: this.env.user,
password: this.env.password,
database: this.env.database
}).then(function(con){
this.connection = con;
return con.state === 'authenticated';
}).catch(function (err) {
console.log(err);
return false;
});
我想保护 this.connection 中的 con 我的问题是我无法同时在函数中获得 con 和 this 。如果您碰巧知道可以帮助我理解这一点的链接,我将不胜感激。
解决方案
this
在传递给的匿名函数内.then()
是全局范围。您可以使用箭头功能来保存this
.
const o = class {
constructor() {
this.n = 0;
}
createConnection() {
// this within arrow function references the curren `class`
return Promise.resolve(this.state()).then(state => this.n = state + 1).then(state => console.log(this.state()))
}
state() {
return this.n;
}
}
let x = new o();
x.createConnection();
我不确定是什么
.apply(this, [con]))
旨在实现所使用的匿名函数。
另一种方法可能是使用名称定义函数并使用Function.protototype.bind()
function handlePromise(data) {
console.log(data, this)
}
const o = {abc:123}
Promise.resolve({def:456})
.then(handlePromise.bind(o))
推荐阅读
- android - 使用深度/通用链接时,iOS 上是否存在“App Picker”?
- php - Laravel 6 用户身份验证页面无法正常工作
- javascript - Javascript中的排序属性被破坏
- bash - 为什么用 &> 重定向会改变 zsh 中的退出代码?
- angular - Angular 8 的子路由配置
- pandas - pandas 中是否有任何内置函数可以减去各种列来操作堆积条形图?
- angular - 防止在jsPDF中将文本拆分为两页
- java - 使用 Fragment 中的按钮在 recyclerview 中发送数据
- c# - 删除富文本格式,同时在 MVC 视图中保留换行符
- if-statement - 我如何在 twig 中实现一个工作 if 语句?我的不工作