Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 22
  1. #1
    Regular Coder
    Join Date
    Jun 2006
    Location
    UK
    Posts
    922
    Thanks
    302
    Thanked 3 Times in 3 Posts

    Question Prototyping in JS. Whats the need?

    Hi

    can someone please explain me whats the need of prototyping in javascript?

    What I mean to say is, when you add a method/property to an object using "Function.prototype" syntax, why cannot you directly add that method inside that object when creating it?

    Consider the following example:

    Instead of doing this:
    Code:
    myobj = function(fname){
     this.fname = fname;
    };
    
    myobj.prototype.age = function (age) {
       this.age = age;
    };
    
    var x = new myobj('joe');
    alert(x.fname);
    x.age = 32;
    alert (x.age);
    I can do this:
    Code:
    myobj = function(fname, age){
     this.fname = fname;
      this.age = age;
    };
    
    
    
    var x = new myobj('joe', 32);
    alert(x.fname);
    alert (x.age);
    So what do we need prototype for?

    Any explanations will be appreciated.

    Thanks

  • #2
    Regular Coder
    Join Date
    Aug 2010
    Posts
    974
    Thanks
    19
    Thanked 212 Times in 210 Posts
    JavaScript is a prototypical language, read this ...
    http://en.wikipedia.org/wiki/Prototy...ed_programming

  • Users who have thanked DaveyErwin for this post:

    phantom007 (08-13-2013)

  • #3
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    If you use the prototype for attaching methods then you have one copy of the method shared between all the objects that use it. If you don't use prototype then each object will have its own separate copy of the method.

    1. A separate copy for each uses more memory.
    2. If you have code to change the method then having one copy is easier to change than having an unknown number of separate copies.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • Users who have thanked felgall for this post:

    phantom007 (08-12-2013)

  • #4
    New Coder
    Join Date
    Aug 2013
    Posts
    50
    Thanks
    0
    Thanked 11 Times in 11 Posts
    Prototypal inheritance, sir. Research it.

  • Users who have thanked joesimmons for this post:

    phantom007 (08-13-2013)

  • #5
    Regular Coder
    Join Date
    Jun 2006
    Location
    UK
    Posts
    922
    Thanks
    302
    Thanked 3 Times in 3 Posts

    Question

    Quote Originally Posted by felgall View Post
    If you use the prototype for attaching methods then you have one copy of the method shared between all the objects that use it. If you don't use prototype then each object will have its own separate copy of the method.

    1. A separate copy for each uses more memory.
    2. If you have code to change the method then having one copy is easier to change than having an unknown number of separate copies.

    Hi

    Mind explaining this with an example?


    Thanks

  • #6
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by cancer10 View Post
    Mind explaining this with an example?
    Code:
    Array.prototype.shuffle = function() {
       var s = [];
       while (this.length) s.push(this.splice(Math.random() * this.length, 1)[0]);
       while (s.length) this.push(s.pop());
       return this;
    }; 
    
    var a = [0,1,2,3,4,5,6,7,8,9]; // defines an array called 'a'
    var b = [9,8,7,6,5,4,3,2,1,0]; // defines an array called 'b'
    var c = a.shuffle();
    var d = b.shuffle();
    var e = c.shuffle();
    alert(a);
    alert(b);
    alert(c);
    alert(d);
    alert(e);
    Because the shuffle method is added to the Array.prototype that single copy of the code can be run for any array including arrays created by that method. If you did not add it to the ptototype then the shuffle method would need a separate copy for each of the arrays instead of sharing the one copy between all arrays.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • Users who have thanked felgall for this post:

    phantom007 (08-12-2013)

  • #7
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    Quote Originally Posted by felgall View Post
    Code:
    Array.prototype.shuffle = function() {
       var s = [];
       while (this.length) s.push(this.splice(Math.random() * this.length, 1)[0]);
       while (s.length) this.push(s.pop());
       return this;
    }; 
    
    var a = [0,1,2,3,4,5,6,7,8,9]; // defines an array called 'a'
    var b = [9,8,7,6,5,4,3,2,1,0]; // defines an array called 'b'
    var c = a.shuffle();
    var d = b.shuffle();
    var e = c.shuffle();
    alert(a);
    alert(b);
    alert(c);
    alert(d);
    alert(e);
    Because the shuffle method is added to the Array.prototype that single copy of the code can be run for any array including arrays created by that method. If you did not add it to the ptototype then the shuffle method would need a separate copy for each of the arrays instead of sharing the one copy between all arrays.
    Hmm. that does not shuffle the shuffled arrays. Simple test/inspection of results reveals.

    What is wrong wth:-

    Code:
    <script type = "text/javascript">
    
    function shuffle(Arr) {
    var NewArr = Arr.slice(0);  // copy the array
    var len = NewArr.length;
    while (len>0) {
    NewArr.push(NewArr.splice(Math.floor(Math.random()*len),1)[0]);
    len--;
    }
    return NewArr;
    }
    
    
    var a = [0,1,2,3,4,5,6,7,8,9]; // defines an array called 'a'
    var b = [9,8,7,6,5,4,3,2,1,0]; // defines an array called 'b'
    var c = shuffle(a);
    var d = shuffle(b);
    var e = shuffle(c);
    alert("A: " + a);
    alert("B: " + b);
    alert("C: " + c);
    alert("D: " + d);
    alert("E: " + e);
    
    </script>

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    phantom007 (08-12-2013)

  • #8
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,371
    Thanks
    11
    Thanked 591 Times in 572 Posts
    you can tack-on prototype methods and properties at any time, but adding own properties would require modifying the constructor code, which might not always be feasible or practical. felgall's array prototype is a good example of this. it's easier to decorate something that already exists and is working, rather than duplicate a bunch of functionality in a "sub class".
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%

  • Users who have thanked rnd me for this post:

    phantom007 (08-12-2013)

  • #9
    Regular Coder
    Join Date
    May 2012
    Location
    France
    Posts
    224
    Thanks
    0
    Thanked 32 Times in 30 Posts
    Not to alter the original array, I would prefer, like Philip M, this variant
    Code:
    <script type="text/javascript">
     Array.prototype.shuffle = function() {
       var r=[],c = this.slice(0); // an Array for response an a copy of the original Array
       while (c.length) r.push(c.splice(Math.random() * c.length, 1));
       return r;
    }; 
    var a = [0,1,2,3,4,5,6,7,8,9]; // defines an array called 'a'
    var b = [9,8,7,6,5,4,3,2,1,0]; // defines an array called 'b'
    var c = a.shuffle();
    var d = b.shuffle();
    var e = c.shuffle();
    alert('a '+a);
    alert('b '+b);
    alert('c=s(a) '+c);
    alert('d=s(b) '+d);
    alert('e=s(c) '+e);
    </script>
    </body>
    Last edited by 007julien; 08-12-2013 at 12:09 PM.

  • Users who have thanked 007julien for this post:

    phantom007 (08-12-2013)

  • #10
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,335
    Thanks
    13
    Thanked 348 Times in 344 Posts
    another use of prototyping is separating methods from properties in loops, since in JS there is no differentiation between them like in class based languages (functions are regular objects).

    PHP Code:
    // primitives and functions on the same level
    var obj1 = {
      
    1,
      
    2,
      
    : function() { return 0; }
    };
    for (
    prop in obj1) {
      
    console.log(prop); // a, b, c
    }
    console.log(Object.keys(obj1)); // [a, b, c]

    // primitives and functions on a different level
    var obj2 Object.create({ : function() { return 0; } });
    obj2.1;
    obj2.2;
    for (
    prop in obj2) {
      
    console.log(prop); // a, b, c (not necessarily in that order)
    }
    console.log(Object.keys(obj2)); // [a, b] 
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  • Users who have thanked Dormilich for this post:

    phantom007 (08-13-2013)

  • #11
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,869
    Thanks
    79
    Thanked 4,421 Times in 4,386 Posts
    Quote Originally Posted by felgall View Post
    Code:
    Array.prototype.shuffle = function() {
       var s = [];
       while (this.length) s.push(this.splice(Math.random() * this.length, 1)[0]);
       while (s.length) this.push(s.pop());
       return this;
    }; 
    
    var a = [0,1,2,3,4,5,6,7,8,9]; // defines an array called 'a'
    var b = [9,8,7,6,5,4,3,2,1,0]; // defines an array called 'b'
    var c = a.shuffle();
    var d = b.shuffle();
    var e = c.shuffle();
    alert(a);
    alert(b);
    alert(c);
    alert(d);
    alert(e);
    Ummm...Philip misspoke. Or perhaps his meaning simply wasn't clear (at least to me). That *does* shuffle the arrays, but it shuffles AND REPLACES the given array.

    That is, for example, when you do var d = b.shuffle() you end up shuffling b *IN PLACE* and then assigning that shuffled version to d, resulting in two arrays with the same content. (Or, more correctly, two variables referencing the same array object.)

    And because of the use of this.splice(), you lose the original array.

    Julien's solution fixes that (or changes that, if it was intended behavior).
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    phantom007 (08-13-2013)

  • #12
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Old Pedant View Post
    Julien's solution fixes that (or changes that, if it was intended behavior).
    So my example turned out better than I thought because it illustrates that to fix a problem such as this one that as prototype was used there is only the one copy of the code that needs to be altered to apply the fix.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • Users who have thanked felgall for this post:

    phantom007 (08-13-2013)

  • #13
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,869
    Thanks
    79
    Thanked 4,421 Times in 4,386 Posts
    слишком много правды !!

    Too much truth!
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    phantom007 (08-13-2013)

  • #14
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    Quote Originally Posted by Old Pedant View Post
    Ummm...Philip misspoke. Or perhaps his meaning simply wasn't clear (at least to me). That *does* shuffle the arrays, but it shuffles AND REPLACES the given array.

    That is, for example, when you do var d = b.shuffle() you end up shuffling b *IN PLACE* and then assigning that shuffled version to d, resulting in two arrays with the same content. (Or, more correctly, two variables referencing the same array object.)

    And because of the use of this.splice(), you lose the original array.

    Julien's solution fixes that (or changes that, if it was intended behavior).
    For the life of me I do not see the use of "two arrays with the same content. (Or, more correctly, two variables referencing the same array object.)".
    How can it make sense to lose/replace the original array? That was the point I was trying to make.


    FWIIW, I have been involved with Javascript for 15 years and I think that I understand prototypes. But I have never had an occasion to use one or found any situation when one was necessary. I admit that I have never been involved in really large code projects.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    phantom007 (08-13-2013)

  • #15
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Philip M View Post
    But I have never had an occasion to use one or found any situation when one was necessary.
    Does that mean that you have never needed to define methods for objects - since the prototype always gets used when adding methods so that the one set of code can be shared?

    Presumably you have also never needed to implement classical inheritance in JavaScript since that requires both the prototype and constructor properties in order to do it properly.

    There are many other things only possible in JavaScript using prototype - including the many things that can be done in a prototyping language that you can't do in an OO language.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • Users who have thanked felgall for this post:

    phantom007 (08-13-2013)


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •