user705414
user705414

Reputation: 21200

The difference between the method defined using the following two

Snippet1:

 var box = function() {};

 box.prototype.open = function {
 };

Snippet2:

  var box = function() {
      this.open = function() {
      };
  }

Any difference between those two, which one is better?

Upvotes: 4

Views: 65

Answers (2)

Diode
Diode

Reputation: 25135

@am not i am is correct. First method is the efficient way to do it. Second method is useful if you need private variables.

var box = function() {
     var _message = "hello world";
     this.func2 = function(){
       console.log(_message);   // prints hello world
     }
};

box.prototype.func1 = function() {
     this.func2();              // prints hello world
     console.log(_message);     // throws ReferenceError: _message is not defined 
};

Upvotes: 5

user1106925
user1106925

Reputation:

Shall we assume that box is a constructor, so you're doing new box()?

If so...

  • The first version will share the open function among all objects created from the box constructor.

  • The second will generate a new function object for every object created from the box constructor.

As such, the first will be more memory efficient than the second.


First version:

    new box                 box prototype            object prototype
+--------------+          +--------------+          +--------------+
|              |          |              |          |              |
|              |--------->|  open func   |--------->|              |
|              |       /  |              |          |              |
+______________+      /   +______________+          +______________+
                     /
                    /
    new box        /
+--------------+  /
|              | /
|              |/
|              |
+______________+

Second version:

    new box                box prototype            object prototype
+--------------+          +--------------+          +--------------+
|              |          |              |          |              |
|  open func   |--------->|              |--------->|              |
|              |       /  |              |          |              |
+______________+      /   +______________+          +______________+
                     /
                    /
    new box        /
+--------------+  /
|              | /
|  open func   |/
|              |
+______________+

Upvotes: 5

Related Questions