简体   繁体   English

Javascript将此参数传递给其他函数

[英]Javascript pass this and other param to function

I have a node application that has a server object. 我有一个具有服务器对象的节点应用程序。 This object has the function connect(). 该对象具有connect()函数。 It is supposed to return a boolean and store the connection in the this of the object. 应该返回一个布尔值并将连接存储在对象的this中。 I can either get the con or the this. 我可以得到骗局或这个。

Example of a function where this is not undefined: 并非未定义的函数示例:

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;

        });

Example of a function where con is not undefined: 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;

        });

I want to safe the con in this.connection my problem is I can't get con and this in the function at the same time. 我想确保this.connection中的con安全,我的问题是我无法同时获得con和this在函数中。 If you happen to know a link that can help me understand this I'd be grateful. 如果您碰巧知道一个可以帮助我理解这一点的链接,我将不胜感激。

this within an anonymous function passed to .then() is the global scope. this传递给一个匿名函数内.then()是全球范围内。 You can use arrow function to preserve this . 您可以使用箭头功能保留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(); 

Am not certain what 不确定是什么

.apply(this, [con]))

is intended to achieve as to the anonymous functions used. 旨在实现所使用的匿名功能。

Another approach could be to define the function with a name and use Function.protototype.bind() 另一种方法是使用名称定义函数并使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM