Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Where to put prototype function

I wonder what is the difference between these two approaches. They both work but I don't understand if the 2nd approach might have undesirable implications?

// A. Putting a prototype method outside the function declaration (what I would normally do)
var Cat = function(){
}

Cat.prototype.eat = function(){
    // implementation
}

// B. Putting a prototype method inside the function declaration (it works too but the scoping seems different)
var Cat = function(){

    Cat.prototype.eat = function(){
        // implementation
    }   
}
like image 412
ChrisRich Avatar asked Apr 19 '26 00:04

ChrisRich


2 Answers

You probably want to do the first example. Both are doing the exact same thing, although technically the second function will have access to the Cat's "private" variables. However, if you want to do that, the correct way to do it is using this:

var Cat = function(){
    var a = 'hi';

    this.eat = function() {
        alert(a); // Exists!
    }
}

Keep in mind that with the above example, or with your original "B" example, the eat function will not exist until you instantiate a new Cat with new Cat(). Meaning, if you just want to call Cat.eat() on the function itself, like a utility method, then the first example with prototype is the way to go.

like image 64
Andy Ray Avatar answered Apr 20 '26 12:04

Andy Ray


Every object has a prototype. Prototypical inheritance allows you to assign either an entirely new prototype (similar to the classical inheritance):

function Animal() {
    this.numLegs = 4;
}
function Cat() {
    // Implementation
}
Cat.prototype = new Animal();

var kitten = new Cat();
console.log(kitten.numLegs); // 4

Or directly add variables and methods to the current class's prototype:

function Cat() {
    // Implementation
}
Cat.prototype.numLegs = 4;

var kitten = new Cat();
console.log(kitten.numLegs); // 4

Your second example simply reassigns the eat function to the Cat prototype every time the Cat class is initiated, which is useless but doesn't take up any memory because it just overwrites the old value.

Why is this useful? Remember that functions are objects. For every instance of your class, each variable and function defined in that class takes up it's own memory. Using prototypical inheritance, you can share common methods, thus not taking up the extra memory for each instance.

Why is this not as useful? You don't have access to private variables.

Keep in mind that this is not the same thing as a static method, which can be declared as:

Cat.feed = function(kittens) {
    for (var kitten in kittens) {
        kitten.eat();
    }
};
like image 32
Wex Avatar answered Apr 20 '26 13:04

Wex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!