我只是想知道“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('/');
});
};
}
答案 0 :(得分:4)
Normamally this
表示调用函数的上下文
在您的情况下,这个函数本身就是一个独立的,所以this
表示当前的浏览器窗口/文档
答案 1 :(得分:1)
我认为该函数实际上是一个要实例化的对象。我想你会在代码中的某处找到类似var myeditctrl = new EditControl(...)的东西。在这种情况下,这指的是myeditctrl对象。