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?

AsherMaximum
  • 942
  • 2
  • 11
  • 17
  • 1
    See http://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript, http://stackoverflow.com/questions/5912497/what-is-difference-between-define-function-by-prototype-and-class-property, http://stackoverflow.com/questions/4270388/what-is-the-difference-between-assigning-a-function-via-this-vs-prototype, http://stackoverflow.com/questions/1441212/javascript-instance-functions-vs-prototype-functions and others – Crescent Fresh Jun 04 '11 at 00:06

1 Answers1

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

Rizwan Sharif
  • 1,089
  • 2
  • 10
  • 20