开发者

prototype and methods - which one is preferred?

Why is using prototype for methods preferrable in js? When I create a new object for both, do they do the same thing?

function Rectangle(w, h) {
    this.width = w;
    this.height = h;
    this.area = function( ) { return this. width * this. height; }
}

or

Rectangle.prot开发者_Go百科otype.area = function(){
    return this.width * this.height
}


There's a big difference. Although both (as you've defined them) will give you the same return value when you call .area() on a Rectangle instance, in your first example, each and every Rectangle object gets its own copy of the area function. In the second case, they all share a single copy (which is more memory-efficient).

Which is preferred depends a great deal on the problem you're solving. In your example, almost certainly use the prototype. And that's usually the way you want to go. But if you have, say, a Foo constructor function and there will never be very many Foo instances and you think it's vitally important that Foo have truly private data, then you might use the private members idiom:

function Foo() {
    var trulyPrivateVariable;

    this.getVar = function() {
        return trulyPrivateVariable;
    };
    this.putVar = function(v) {
        // Presumably some logic or checks here
        trulyPrivateVariable = v;
    };
}

This pattern makes use of the fact that the functions are closures over the trulyPrivateVariable local variable in the constructor function.

Again, though, remember that those functions are duplicated for every instance, so this is only appropriate in moderation.

Worth noting that these are not mutually-exclusive. You can follow on the Foo above with:

Foo.prototype.doSomething = function() {
    // Do something completely unrelated -- note that code here
    // does not have access to `trulyPrivateVariable`, although it
    // will have access to `this.getVar()` and `this.putVar()`
    // (assuming it's called in the normal way).
};

...so that you get as much reuse as you can, by only putting the parts that absolutely need access to trulyPrivateVariable inside the constructor function where they'll get duplicated.

Off-topic: I've used anonymous functions (as you did) throughout above for brevity, but I'm not a fan of them in production code.


using prototype is preferable. It is a more efficient way for JS to store which methods are available to a "class". You should look at some tutorials on object oriented javascript, and on prototypal inheritance.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜