扩展$ resource对象从Factory中删除原型

时间:2016-09-10 23:39:53

标签: javascript angularjs javascript-objects angularjs-resource

以下是我现在的代码:

// 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的原型函数。

1 个答案:

答案 0 :(得分:1)

根据documentation angular.extend仅复制拥有的可枚举属性。原型属性可以是可枚举的,但它们不属于对象本身,因此不符合自己的。 MDN有一篇关于此here的文章。