如何使用 .bind() 来绑定 this 的值?

How to use .bind() to tie down the value of this?

这可能是一个愚蠢的问题,但在以下情况下我可以使用什么模式来使用 bind 方法来限制 this[=15= 的值] 在下面代码的一个方法中。

'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
};