扩展 $resource 对象从 Factory 中移除原型
Extending $resource object removes prototype from Factory
这是我现在拥有的代码:
// Factory
angular.factory('Student', function() {
var defaults = {
StudentId: null
};
var Student = function(params) {
angular.extend(this, angular.copy(defaults), params);
};
// Prototype function for Student
Student.prototype.hasStudentId = function() {
return this.StudentId != null;
};
});
// Service
angular.service('StudentService', ['Student', '$resource', function(Student, $resource) {
var service = {};
service.student = $resource('student/:studentId'. {} { load: {method: 'GET'} });
service.loadStudent = function(studentId) {
var currentStudent = service.student.load(studentId); // HTTP call
currentStudent.$promise.then(function() {
// I expect the object currentStudent would have hasStudentId() prototype function, but it's not
angular.extend(currentStudent, new Student(currentStudent));
// However, if I use 'new' keyword, studentObj has prototype hasStudentId() function
var studentObj = new Student(currentStudent);
});
};
return service;
}]);
如您所见,在我扩展currentStudent
对象后,currentStudent 没有原型函数hasStudentId()
。但是,如果我使用 new Student(currentStudent)
,它就会正确地具有原型功能。
Angular.extend 是否忽略 prototype
函数?
目前,currentStudent
对象只有$resource
的原型函数。
根据 documentation angular.extend
only copies own enumerable properties. Prototype properties may be enumerable but they do not belong to the object itself and, therefore, do not qualify as own. MDN has an article on this here.
这是我现在拥有的代码:
// Factory
angular.factory('Student', function() {
var defaults = {
StudentId: null
};
var Student = function(params) {
angular.extend(this, angular.copy(defaults), params);
};
// Prototype function for Student
Student.prototype.hasStudentId = function() {
return this.StudentId != null;
};
});
// Service
angular.service('StudentService', ['Student', '$resource', function(Student, $resource) {
var service = {};
service.student = $resource('student/:studentId'. {} { load: {method: 'GET'} });
service.loadStudent = function(studentId) {
var currentStudent = service.student.load(studentId); // HTTP call
currentStudent.$promise.then(function() {
// I expect the object currentStudent would have hasStudentId() prototype function, but it's not
angular.extend(currentStudent, new Student(currentStudent));
// However, if I use 'new' keyword, studentObj has prototype hasStudentId() function
var studentObj = new Student(currentStudent);
});
};
return service;
}]);
如您所见,在我扩展currentStudent
对象后,currentStudent 没有原型函数hasStudentId()
。但是,如果我使用 new Student(currentStudent)
,它就会正确地具有原型功能。
Angular.extend 是否忽略 prototype
函数?
目前,currentStudent
对象只有$resource
的原型函数。
根据 documentation angular.extend
only copies own enumerable properties. Prototype properties may be enumerable but they do not belong to the object itself and, therefore, do not qualify as own. MDN has an article on this here.