Вероятно, это тупой вопрос, но какой шаблон я могу использовать в следующей ситуации, чтобы использовать метод привязки, чтобы связать значение этого внутри метода в приведенном ниже коде.
'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;
};
};
См. 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
};