Как использовать .bind (), чтобы связать значение этого?

0

Вероятно, это тупой вопрос, но какой шаблон я могу использовать в следующей ситуации, чтобы использовать метод привязки, чтобы связать значение этого внутри метода в приведенном ниже коде.

'use strict';

exports.service = function() {
    this.colors = [];
    this.years = [];
    this.trims = [];
    var scope = this;

    this.setColors = function(colorsArr) {
        scope.colors = colorsArr;
    };

    this.setYears = function(yearsArr) {
        scope.years = yearsArr;
    };

    this.getVehicleDetails = function() {
        return {
            colors: scope.colors,
            years: scope.years
        };
    };

    this.getTrims = function() {
        return trims;
    };
};
Теги:
binding

1 ответ

0
Лучший ответ

См. bind ко всем методам. Затем вы можете использовать this всех внутренних методах.

'use strict';

exports.service = function() {
    this.colors = [];
    this.years = [];
    this.trims = [];

    this.setColors = function(colorsArr) {
        this.colors = colorsArr; // Use this here
    }.bind(this); // Change of context

    this.setYears = function(yearsArr) {
        this.years = yearsArr; // Use this here
    }.bind(this); // Change of context

    this.getVehicleDetails = function() {
        return {
            colors: this.colors, // Use this here
            years: this.years // Use this here
        };
    }.bind(this); // Change of context

    this.getTrims = function() {
        return this.trims; // Use this here
    }.bind(this); // Change of context
};

Ещё вопросы

Сообщество Overcoder
Наверх
Меню