【发布时间】:2013-03-05 11:45:59
【问题描述】:
我只是想知道“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!!!
以上sn-p取自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('/');
});
};
}
【问题讨论】:
-
好吧,
typeof总是打印变量的 type,如果this是一个 EditCtrl,它仍然是一个对象,所以它是正确的。请记住,typeof永远不会告诉您对象的“类”,您应该尝试完整记录它并查看它是什么。 -
马泰奥:谢谢。那么如何判断一个对象是否是一个函数呢?我应该使用什么关键字或反射技巧?
标签: javascript function angularjs this