0

For exampleis this:

function obj(val) {
    this.val = val;
}
obj.prototype.newfunction = function(){
    return this.val;
};

Different than this in any way at all?

function obj(val) {
    this.val = val;
    this.newfunction = function(){
        return this.val;
    }
}

I realize that the reason for prototype is so that you can add methods to objects that you didn't create, but is there any reason to use the second block over the first, or vice versa?

1

1 Answer 1

3

With first approach you cannot call obj.newfunction() , with the second one you can.

when you extend prototype with extra functionality (like in your first example) , this extra functionality will be available to all the objects you create from this function with new operator.but this functionality does not become part of function itself. When you extend prototype all existing objects from this function will immediately see all the changes.

For second case , you are making newfunction a property of obj function itself.

I recommend you read this post , it will help to clarify the concepts of prototype property http://joost.zeekat.nl/constructors-considered-mildly-confusing.html

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

1 Comment

And, just to be specific, new obj().newfunction() works in both cases.

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.