0

我只是想知道“ this”关键字在以下函数的上下文中指的是什么:

function EditCtrl($scope, $location, $routeParams, Project) {
  var self = this;

  Project.get({id: $routeParams.projectId}, function(project) {
    self.original = project;
    $scope.project = new Project(self.original);
  });

  $scope.isClean = function() {
    return angular.equals(self.original, $scope.project);
  }

  $scope.destroy = function() {
    self.original.destroy(function() {
      $location.path('/list');
    });
  };

  $scope.save = function() {
    $scope.project.update(function() {
      $location.path('/');
    });
  };
}

特别是,我会认为“ this”指的是EditCtrl功能,但console.log(typeof this);打印object

上面的片段取自http://angularjs.org/#project-js

编辑:这是完整的代码。对不起:我应该把它放在首位......

angular.module('project', ['mongolab']).
  config(function($routeProvider) {
    $routeProvider.
      when('/', {controller:ListCtrl, templateUrl:'list.html'}).
      when('/edit/:projectId', {controller:EditCtrl, templateUrl:'detail.html'}).
      when('/new', {controller:CreateCtrl, templateUrl:'detail.html'}).
      otherwise({redirectTo:'/'});
  });


function ListCtrl($scope, Project) {
  $scope.projects = Project.query();
}


function CreateCtrl($scope, $location, Project) {
  $scope.save = function() {
    Project.save($scope.project, function(project) {
      $location.path('/edit/' + project._id.$oid);
    });
  }
}


function EditCtrl($scope, $location, $routeParams, Project) {
  var self = this;

  Project.get({id: $routeParams.projectId}, function(project) {
    self.original = project;
    $scope.project = new Project(self.original);
  });

  $scope.isClean = function() {
    return angular.equals(self.original, $scope.project);
  }

  $scope.destroy = function() {
    self.original.destroy(function() {
      $location.path('/list');
    });
  };

  $scope.save = function() {
    $scope.project.update(function() {
      $location.path('/');
    });
  };
}
4

2 回答 2

4

通常this是指调用函数的上下文

在您看来,此功能独立于自身,因此this意味着当前浏览器窗口/文档

于 2013-03-05T11:50:28.223 回答
1

我会假设该函数实际上是一个要被实例化的对象。我想你会在代码的某处找到类似 var myeditctrl = new EditControl(...) 的东西。在这种情况下,这指的是 myeditctrl 对象。

于 2013-03-05T11:55:14.130 回答