开发者

A question about object declaration in Javascript

What's the difference between this:

function Book() {
    this.title = '';

    this.setTitle = function(title) {
        this.title = title;
    }
}

or this:

function Book() {
}
Book.prototype.title = '';
Bo开发者_开发知识库ok.prototype.setTitle = function(title) {
    this.title = title;
}

Is there any difference other than the syntax?


You should probably read about prototypes.

In the first example you set the function setTitle on that very Book instance that gets created.

In the second example you're using prototypal inheritance, in other words all Books now inherit the same setTitle function.

The second one saves memory and the functions are easier to "update" across all the Book instances.

But the first one has it's use cases, since you can leave out the this on title and make the variable private through the use of closures.

function Book(title) {
    var title = title;

    this.getTitle = function() { // function keeps a reference to title
        return title; // now we only have a getter, but no setter for title
                      // thus title is essentially private
    }
}


When using Book.prototype.setTitle only one setTitle-function is created, and is reused for all future instances of Book.

In the first example every instance of Book will create each own setTitle-function.

Hence, using prototype is recommended.


the first will set the title property and the setTitle method directly on an instance of Book. the second sets those members on the prototype of Book. The second is generally the better approach for OOP JavaScript.


This excellent SO question from yesterday will explain the differences between your two examples: Why is JavaScript prototyping?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜