What style do you use for creating a "class"? *

Question

There are a few ways to get class-like behavior in javascript, the most common seem to be prototype based like this:

function Vector(x, y, x) {
    this.x = x;
    this.y = y;
    this.z = z;
    return this;
}

Vector.prototype.length = function () { return Math.sqrt(this.x * this.x ... ); }

and closure based approaches similar to

function Vector(x, y, z) {
    this.length = function() { return Math.sqrt(x * x + ...); }
}

For various reasons the latter is faster, but I've seen (and I frequently do write) the prototype version and was curious as to what other people do.

Answer

Assigning functions to the prototype is better (for public methods) because all instances of the class will share the same copy of the method. If you assign the function inside the constructor as in the second example, every time you create a new instance, the constructor creates a new copy of the length function and assigns it to just that one instance.

However this latter technique is useful if you want each copy to have it's own copy, the main use of that being to do private/privileges methods which have access to private variables declared inside the constructor and inherited via the closure mechanism.

Douglas Crockford has a good summary.

< br > via < a class="StackLink" href=" http://stackoverflow.com/questions/6499/" >What style do you use for creating a "class"?< /a>
Share on Google Plus

About Cinema Guy

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment