首页 > 解决方案 > 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 。如果您碰巧知道可以帮助我理解这一点的链接,我将不胜感激。

标签: javascriptasynchronousthis

解决方案


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))


推荐阅读