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.
Results 1 to 3 of 3

Thread: .prototype

  1. #1
    Regular Coder
    Join Date
    Apr 2007
    Posts
    179
    Thanks
    17
    Thanked 0 Times in 0 Posts

    .prototype

    I saw two kinds of coding:

    1)

    var obj = new Object();

    obj.addEvent=function(a, b, c){...}


    2) obj.prototype.someFunc=function(){...}


    My question:

    Why sometimes use .prototype sometime not? or under what circumstance should use .prototype, while others not?


    Thanks


    Scott

  • #2
    Senior Coder
    Join Date
    Sep 2005
    Posts
    1,791
    Thanks
    5
    Thanked 36 Times in 35 Posts
    when you add a method to an object's prototype (whether it be 'Object' itself, 'Array', 'String', 'Number' or any of the other built-in types, or to a class you've declared yourself) it will be available to all instances of that object. Adding the method to the instance means it's only available to that instance. Some examples, I'll use a user-defined class:
    Code:
    var Dog = function(name) {
      this.name = name;
    };
    var fido = new Dog('fido');
    
    //we give 'fido' a 'bark()' method
    fido.bark = function() {
      alert(this.name+" says woof!");
    };
    fido.bark();  //and this will work
    
    //if we try this though, we'll get an error: 'spot.bark is not a function'
    var spot = new Dog('spot');
    spot.bark();
    
    //but if we add the method to the class's prototype:
    Dog.prototype.bark = function() {
      alert(this.name+" says Woof!");
    }
    
    //then both of these work
    fido.bark();
    spot.bark();
    (If you run the above code as a single script, it will break and stop where I say it does, to see the 'working' code below, take out the first 'spot.bark()' line)
    My thoughts on some things: http://codemeetsmusic.com
    And my scrapbook of cool things: http://gjones.tumblr.com

  • #3
    Regular Coder
    Join Date
    Apr 2007
    Posts
    179
    Thanks
    17
    Thanked 0 Times in 0 Posts
    Many Thanks. --Scott


  •  

    Posting Permissions

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