Javascript:在嵌套范围内访问/绑定父上下文/此方法的最佳方法

时间:2016-08-24 17:06:45

标签: javascript

示例代码:

render: function() {
  this.getAsyncData(function() {
    this.specialFunction = (function(){
      //make nested calls again    
    }.bind(this));

    this.specialFunction();
  }.bind(this));
}

以下是一些有道理的方法 -

  1. 使用bind()方法
  2. 使用var self = this;,然后使用内部自我
  3. 请列出访问父上下文的所有其他可能方式。

1 个答案:

答案 0 :(得分:0)

在ES6中,如果要保持相同的上下文,可以使用胖箭头。

它等于ES6代码:

function Person() {
  this.age = 0;

  setInterval(() => {
    this.age++; // |this| properly refers to the person object
  }, 1000);
}

var p = new Person();

它等同于ES5代码:

function Person() {
  var _this = this;

  this.age = 0;

  setInterval(function () {
    _this.age++; // |this| properly refers to the person object
  }, 1000);
}

var p = new Person();

您可以在此处阅读有关箭头功能的更多信息https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

在Angular中,您可以使用vm来更好地处理范围并避免嵌套范围的问题。它自Angular添加controller as语法后可用。

通过使用此功能,您可以在不使用$ scope。$ parent的情况下访问所需的任何范围。它还为您提供了更好的可读性,并使代码更易于理解。

<div ng-controller="ShopController as shop">
  <p>{{ shop.name }}</p>
  <div ng-controller="CustomerController as customer">
    <p>{{ shop.address }}</p>
    <p>{{ customer.address }}</p>
  </div>
</div>

您可以在此处阅读更多内容https://johnpapa.net/angularjss-controller-as-and-the-vm-variable/

相关问题