开发者

Access class members from nested functions

i have this class in javascript

var MyGird = Class.extend({
  classMemeber1 : "So开发者_开发知识库me Value"
  ,clickEvent : function(){
        this.editor.on({
            afteredit: function() {
                //
                //  HOW TO I ACCESS classMemeber1 from here? ?
                //
                //
            }
        })
})

how do i access classMemeber1 from inside of afteredit...

Thanks


You need to save a reference to the object invoking clickEvent function by storing this [1] in a variable. It will be available inside the afteredit method because of closure.

var MyGird = Class.extend({
    classMemeber1: "Some Value",
    clickEvent: function () {
        var self = this; // save object reference
        this.editor.on({
            afteredit: function () {
                // access classMemeber1 from here
                // by using the stored reference
                alert(self.classMemeber1);
            }
        });
    },
    // ...
});

[1] this operator in javascript (note: 'this' is not an operator)


If you write ES6, you can use arrow functions: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

In your example, should be something like (not tested):

var MyGird = Class.extend({
    classMemeber1: "Some Value",
    clickEvent: () => {
        this.editor.on({
            afteredit: () => () {
                alert(this.classMemeber1);
            }
        });
    },
    // ...
});


I had a similar problem and solved it using a library call cron.

this library allows you to schedule tasks very easily here is an example of code i used to implement sending a message at a specific time

import {CronJob} from "cron";

sendMessageEveryMinute(message) {
    let bot = this.bot;
    let chatId = this.chatId;
    let job = new CronJob('1 * * * * *', 
        function () {
            bot.telegram.sendMessage(chatId, message).then(r => console.log(r));
    }, null, true, 'Europe/Rome');
}

as you can see (minus the telegram methods) what we do is just declare an object called CronJob which takes as input the so called cron schedule expressions (which is used to define the actual time when the function we want to execute will execute) and the second parameter is the function itself we want to execute at that specific time. The true param that you see is telling that the schedule will start at instantiation time. this means that the schedule will start as the object job gets instantiated. For the other params look at the documentation: cron documentation

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜