What is the difference between extending an object using a prototype or inline?

What's the difference? Whether there is a?

var Likes = function (el) { this.el = $(el); return this; }; Likes.prototype.add = function (name) { this.el.find('.no-results').remove(); $('<li>', { text: name }).appendTo(this.el); }; 

and

 var Likes = function (el) { this.el = $(el); this.add = function (name) { this.el.find('.no-results').remove(); $('<li>', { text: name }).appendTo(this.el); }; return this; }; 
+7
source share
3 answers

The difference is how the object is created. When you define functions on a prototype of an object, it defines ONCE for each subsequent instance of that object.

If you declare functions at the instance level, they become overridden every time you declare a function.

In fact, this affects the performance of http://jsperf.com/prototype-vs-instance-functions

It is generally recommended that you use a prototype for functions that will be reused across multiple instances of the constructor. For example, if you use the new operator to create constructor instances ..

 var Likes = function (el) { this.el = $(el); return this; }; Likes.prototype.add = function (name) { this.el.find('.no-results').remove(); $('<li>', { text: name }).appendTo(this.el); }; var oneLike = new Likes(); var twoLike = new Likes(); var threeLike = new Likes(); 

Since add defined on the prototype of the object, it receives the definition only once, and not every time a Likes instance is created.

+6
source

Yes, there is a difference.

If you use a prototype object, then all created Likes objects will have the same reference to the prototype object. But if you use the second method (this.add), it will add a function to each created object.

The first option is preferable to the second.

+2
source

Example 2 is best practice because it lends itself to the implementation of inheritance rather than making wasteful copies of the properties of an object.

In a small application without inheritance, there is probably not much practical difference between the two examples. But imagine that you had 10,000 instances of the Likes constructor in a more complex application using inheritance. In the second example, each of them will receive a local copy of the add function.

This can theoretically cause memory bottlenecks in a larger application. In addition, if you want to change the add method in the future, you will need to do this on every local object.

+2
source

All Articles