AngularJs 服务函数- this()

AngularJs Service function- this()

我正在学习 angularjs 并且我一直注意到当一个函数被声明时,大多数人通常在修改它之前将 "this" 变成一个 var。这是为什么?

下面的代码片段:

function NameService() {

     var self = this; **THIS BLOCK. WHY??**

    //getName returns a promise which when 
    //fulfilled returns the name.
    self.getName = function() {
      return $http.get('/api/my/name');
    };
}

在底部,示例使用 self.getName。为什么不直接调用 this.getName?

谢谢

这只是您可以使用的一种模式。通常它有助于避免 'this' 关键字的冲突,这在 javascript 'world'.

中很常见

还有助于提高可读性,让您可以更轻松地阅读代码。 查看此示例,您可以在其中轻松区分服务的 public 功能和 local/private 功能:

function NameService() {

    var self = this; **THIS BLOCK. WHY??**

    self.getName = getName;
    self.setName = setName;


    //getName returns a promise which when 
    //fulfilled returns the name.
    function getName() {
        return $http.get('/api/my/name');
    };

    function setName(){
       //blablabla
    }

    function justAHelperFunction(){
        //helper function, kind of inner function, a private function
    }
}

In javascript this 指的是当前对象,并且 this 的值表示方法取决于函数的调用方式。当您将回调传递给函数调用时,this 的上下文会发生变化,并且在回调定义中 this 不会引用具有进一步调用回调函数的方法的对象。

var person = {
  firstName: 'John',
  lastName: 'Doe',

  printFullName: function () {
    setTimeout(function () {
      // here this doesn't point to the person object anymore
      // as the callback passed to setTimeout was invoked by global window object
      // so this points to window
      console.log(this.firstName + ' ' + this.lastName);
    }, 100)
  }
}

要解决上述情况,您希望它是人,您可以为捕获另一个变量中的引用的上下文设置别名。这是上述方法的正确版本。

printFullName: function () {
    var self = this;
    // till now self == this
    setTimeout(function () {
      // here self still points to person whereas this is now pointing to window
      console.log(self.firstName + ' ' + self.lastName);
    }, 100)
  }