简体   繁体   中英

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 = '';
Book.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.

昨天这个优秀的SO问题将解释你的两个例子之间的差异: 为什么JavaScript原型设计?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM