1

i have this object declaration inside an Angular.js module:

    $scope.test=function(){

    };

    $scope.test.prototype.push = function(data) {
        return data;
    };

And i call it like this:

var a = $scope.test.push(1);
console.error(a);

But i get this error:

Error: undefined is not a function (evaluating '$scope.test.push(1)')

Why i cant access to methods that i added via Prototype to my object?

2
  • 2
    The test becomes accessible from objects that you create using test as a constructor function, not from the function object itself, unless you did $scope.test.prototype.push(1);, which would be strange. You can add the push function directly to the $scope.test function if you wish, but I'm not sure what you're after in the end. Commented Jul 1, 2015 at 19:13
  • 1
    You probably want var a = new $scope.test.push(1); and if so the convention would be to name Test from capital letter Commented Jul 1, 2015 at 19:30

1 Answer 1

2

You seem to be mistaking a function's prototype property with the internal prototype of an object.

A relevant quote from the book Eloquent Javascript:

It is important to note the distinction between the way a prototype is associated with a constructor (through its prototype property) and the way objects have a prototype (which can be retrieved with Object.getPrototypeOf). The actual prototype of a constructor is Function.prototype since constructors are functions. Its prototype property will be the prototype of instances created through it but is not its own prototype.

What this means in the context of your code sample:

$scope.test.prototype.push = function(data) {
    return data;
};

Here you've added a push function to the prototype property of the $scope.test function, which will be present on the prototype of objects created by using this test function as a constructor function (with the new keyword).

$scope.test, however, remains an empty function, which has no .push() method, resulting in the error. If you want to add a push method to every function, you could use Function.prototype (note that Function is the constructor with which new functions are created), but I'm not sure where are we going with this.

Sign up to request clarification or add additional context in comments.

1 Comment

i just wanted to add new method to that object. i was thinking prototype is the way, but right now i remove it and code works! $scope.test.push = function (data) {... i don't know it's the proper way by the way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.