View Full Version : .prototype

08-23-2007, 02:15 AM
I saw two kinds of coding:


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?



08-23-2007, 10:14 AM
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:

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');

//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

(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)

08-23-2007, 06:23 PM
Many Thanks. --Scott

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum