我只是想知道的「this
」關鍵字是指在下面的函數的上下文是什麼:「本」的JavaScript函數中的上下文關鍵字
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
EDIT採取:以下是完整的代碼。我很抱歉:我應該在第一時間已包括它...
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'總是打印一個變量的**類型**,如果是'this'是一個EditCtrl的情況,它仍然是一個對象,所以它是正確的。記住'typeof'永遠不會告訴你一個對象的「類」,你應該嘗試完全記錄下來,看看它是什麼。 – 2013-03-05 11:49:15
Matteo:謝謝。那我怎麼知道一個對象是一個函數呢?我應該使用什麼關鍵字或反射技巧? – balteo 2013-03-05 11:54:32