0
  var workViewer = {
    container: document.documentElement,
    popup: document.querySelector('.avgrund-popup'),
    cover: document.querySelector('.avgrund-cover'),

    init: function () {
        this.addClass(this.container, 'avgrund-ready');
        window.avgrund = {
            activate: this.activate,
            deactivate: this.deactivate,
            disableBlur: this.disableBlur
        };
    },
    activateModal: function (state) {
        setTimeout(function () {
            this.parent.removeClass(popup, 'no-transition'); //this line
            this.parent.addClass(this.container, 'avgrund-active');  //this line
        }, 0);
    },


    removeClass: function (element, name) {
        element.className = element.className.replace(name, '');
    }
};


module.exports = workViewer;

I want to pass this into setTimeout function, whats the right way to do it?

This is my first post, please let me know if i can improve it in any way

2
  • var that = this; function() { that.parent... Commented Mar 22, 2016 at 21:58
  • Thank you! this is what i was looking for. Commented Mar 22, 2016 at 22:01

2 Answers 2

7

There's two major ways. The first is saving a reference to this and using it instead:

var self = this;
setTimeout(function() {
  self.parent.removeClass(popup, 'no-transition');
  self.parent.addClass(self.container, 'avgrund-active');
}, 0);

The other is to use bind to create a new function with this bound to the given value.

setTimeout(function() {
  this.parent.removeClass(popup, 'no-transition');
  this.parent.addClass(this.container, 'avgrund-active');
}.bind(this), 0);

If you're running in an environment that supports them, you can also use an arrow function.

setTimeout(() => {
  this.parent.removeClass(popup, 'no-transition');
  this.parent.addClass(this.container, 'avgrund-active');
}, 0);
Sign up to request clarification or add additional context in comments.

Comments

2

You can use Function.prototype.bind(). It creates function which is bounded to the given context:

setTimeout(function () {
    this.parent.removeClass(popup, 'no-transition'); //this line
    this.parent.addClass(this.container, 'avgrund-active');  //this line
}.bind(this), 0);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.