PDA

View Full Version : method vs prototype method


johnmerlino
06-12-2010, 02:43 PM
Hey all, from my understanding you can add a method to a constructor function by declaring it within the function and now it belongs to the object. You can also use prototype to attach a method to an object *after* it's been defined. My question is why would you want to attach a method to the object after it's been defined if you can simply define it when the object is created? I can see no real world use of this. A complex example would be greatly appreciated, because the little short examples I see online like "function dog() { this.bark = function(){"ruff"}}" do not enlighten me with real world application.

Thanks for any response.

gizmo1650
06-12-2010, 03:34 PM
you use prototype to add methods to objects you don't create. For example if i wanted to add a method to Array, which is native code, i need to use the prototype object. example code below.
Array.prototype.unique = function () {
var r = new Array();
o:for(var i = 0, n = this.length; i < n; i++)
{
for(var x = 0, y = r.length; x < y; x++)
{
if(r[x]==this[i])
{
continue o;
}
}
r[r.length] = this[i];
}
return r;
}

johnmerlino
06-12-2010, 03:56 PM
Thanks for nice example. Out of curiosity, I never seen this syntax before "o:" What does this mean? Thanks.

Actually I found it online:
"o:" a label that the continue uses. If it wasn't there the continue would continue the inner loop.

johnmerlino
06-12-2010, 06:04 PM
In the below code, if I remove "this" from call() I get undefined. Why doesn't it just return the weight and height of the super class object (Person)? If I add "this", it returns the weight and height of the instance of Man (in this case the john object), which makes sense if "this" refers to the instance of the Person class, courtesy of new keyword:


<script type="text/javascript">
function Person(h, w) {
this.weight = w;
this.height = h;
}

function Man(h,w,s) {
Person.call(this, h, w); //removing "this" will return null
this.sex = s;
}

Man.prototype = new Person();
Man.prototype.constructor = Man;

averageAdult = new Person(5.10, 165);
john = new Man(5.9, 165, "male");


alert(john.height);

</script>