[英]Javascript pass this and other param to function
我有一個具有服務器對象的節點應用程序。 該對象具有connect()函數。 應該返回一個布爾值並將連接存儲在對象的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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.