【问题标题】:Meteor js Classes and contetMeteor js 类和内容
【发布时间】:2016-02-21 12:52:36
【问题描述】:

我试图在我的项目中使用流星类。在我的课堂上,我使用了一个 npm 模块 nodemailer,它提供了一个自定义处理程序来设置这样的套接字:

var nodemailer = require('nodemailer');

var transport = nodemailer.createTransport({....});

transpot.getSocket = function (options, callback) {  // <-- here
   console.log('get socket');
}

所以我试着用流星代码把它包起来:

var nodemailer = Meteor.npmRequire('nodemailer');

class TestNodemailerMeteor {

    constructor(options) {
           //....  
         this.name = options.name;
    }
    initMailer(){
        this.transport = nodemailer.createTransport({//set options});

        this.transport.getSocket = this.getSocket;


    }
    getSocket(options, callback){
          // 
         console.log(this.name); // this.name is undefined, lost this context here
    }
}

问题是,当从模块调用transport.getSocket 时,我失去了包含所有变量和方法的类上下文。有没有办法在不丢失类上下文的情况下将模块函数附加到类对象方法上?

【问题讨论】:

    标签: javascript node.js class meteor


    【解决方案1】:

    这应该可以通过Function.prototype.bind() 实现。试试这个:

        this.transport.getSocket = this.getSocket.bind(this);
    

    这可能是也可能不是在此处使用 bind 的正确方式,但希望这会引导您走向正确的方向。

    【讨论】:

    • 感谢这对我的帮助。现在我开始了解如何解决上下文问题
    猜你喜欢
    • 2016-03-20
    • 2014-07-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-20
    相关资源
    最近更新 更多