【问题标题】:How to use .bind() to tie down the value of this?如何使用 .bind() 来限制 this 的值?
【发布时间】:2015-06-29 11:30:59
【问题描述】:

这可能是一个愚蠢的问题,但是在以下情况下我可以使用什么模式来使用 bind 方法来将 this 的值绑定在下面代码中的方法中.

'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 取决于调用函数的方式,而不是定义。

标签: javascript angularjs binding


【解决方案1】:

所有方法见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
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-09
    • 1970-01-01
    相关资源
    最近更新 更多