Why do we need “var self = this” in classes in Javascript?

前端 未结 4 1436
后悔当初
后悔当初 2021-02-01 20:54

Why can\'t we directly use this instead of self in the following example?

function SeatReservation(name, initialMeal) {
    var self =          


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-01 21:28

    There's no reason why you can't use this directly there (and I would say it would be better for readability if you did).

    However, the var self = this; is often needed in situations like the following (basically, any asynchronous action like event binding, AJAX handlers etc, where the resolution of this is deferred until it equals something else);

    function SeatReservation(name, initialMeal) {
        var self = this;
        self.name = name;
        self.meal = ko.observable(initialMeal);
    
        setTimeout(function () {
            alert(self.name); // otherwise, this is window; use self to keep a reference to the "SeatReservation" instance.
        }, 100);
    }
    

提交回复
热议问题