javascript - 扩展 $resource 对象从 Factory 中移除原型(prototype)

标签 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 没有原型(prototype)函数hasStudentId()。但是,如果我使用 new Student(currentStudent),它就会正确地具有原型(prototype)函数。

Angular.extend 会忽略 prototype 函数吗?

目前currentStudent对象只有$resource的原型(prototype)函数。

最佳答案

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

关于javascript - 扩展 $resource 对象从 Factory 中移除原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39431557/

相关文章:

javascript - 在 jQuery 上添加默认类

javascript - 如何从javascript中的对象中删除时间?

javascript - 我对从 Web api 到 Angular js 和 html 的 get 方法有疑问

javascript - 如何在 PHP 中访问嵌套数组的变量

javascript - 合并两个对象并增加 ECMAScript 6 中的键

javascript - “this”并不引用它被调用的上下文(对于箭头函数)

javascript - 无法访问对象的属性 - 对象

javascript - 如何用对象数组中的特定索引替换元素-Javascript

javascript - AngularJS 服务取决于第二个服务的资源

javascript - 在 Javascript 中重写 _.find 函数时得到 "undefined"