简体   繁体   中英

Javascript Prototype not adding method

I have the following code in my app:

app.factory('User', ['railsResourceFactory', '$http', function (railsResourceFactory, $http) {
    var res = railsResourceFactory({url: '/users', name: 'user'});

    res.prototype.hello = function () {
        return "hello";

    };

    debugger;

    return res;
}]);

I am using the angularjs-rails-resource gem . When I hit the debugger in chrome and i type the following in the console:

res.hello()

I get:

TypeError: Object function RailsResource(value) { angular.extend(this, value || {}); } has no method 'hello'

I'm not sure why this is happening. I'm sort of new javascript so I may not be fundamentally be understanding something about Prototype. Or maybe it can be an issue with angular or rails.

Thanks

The prototype property is only available to functions.. The first fundamental question to ask yourself is , does

railsResourceFactory({url: '/users', name: 'user'});

return a function / constructor? No. it does not. It returns a resource object. If you come from a classical OOP language, lets just say that the prototype property is only available to classes and not available in objects.. If you still want to be able to access the prototype of the object you are currently dealing with you could access it by calling

object.constructor.prototype

So you can achieve what you are attempting to achieve by calling

res.constructor.prototype.hello= function () {
        return "hello";

    }; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM