【问题标题】:Extending $resource object removes prototype from Factory扩展 $resource 对象从工厂中删除原型
【发布时间】:2017-01-18 18:49:09
【问题描述】:

这是我现在拥有的代码:

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

【问题讨论】:

    标签: javascript angularjs javascript-objects angularjs-resource


    【解决方案1】:

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

    【讨论】:

    • 那我应该用什么来代替 angular.extend?
    • 你为什么不直接用所需的功能丰富你的 $resource 呢?
    • 最简单的方法是只为 $resource 定义原型函数,在这个问题中,您将通过示例找到答案:stackoverflow.com/questions/18138147/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多