0

Related to this question But that solution creating a variable locally doesn't work for me.

My case is:

handleSubmit() {
    var posting = $.post(this.props.url, {...});
    posting.done(function() {
        window.location.href = `/frontend/${this.props.value}`;
    });
}

Since the callback function doesn't have access to this, how should I pass this into the callback? If I'm not going to use Ajax.

1 Answer 1

1

3 ways

Old school - think old IE before IE9

var _this = this;

posting.done(function() {
    window.location.href = `/frontend/${_this.props.value}`;
});

Middle school - think IE9 thru IE 11

posting.done(function() {
    window.location.href = `/frontend/${this.props.value}`;
}.bind(this));

New School - any real browser

posting.done(() => {
    window.location.href = `/frontend/${this.props.value}`;
});

Considering you're using template literals, you're safe to use the "new school" method

Sign up to request clarification or add additional context in comments.

2 Comments

I'm kind of new to JavaScript. Would you mind explain a little bit what is the different between function() {} and () => {}? Why () => {} this way can access to this? Thank you for your time.
explain a little arrow notation () => {} does not have binding to it's own this, rather Arrow functions establish this based on the scope the Arrow function is defined within - arrow functions documentation explains it in great detail - I've lifted what I've said directly from there :p

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.