0

I have this following scenarios. I am defining a new class C and export it as a node module. I wonder what the differences are between using a plain function (method 1) vs. using a prototype method (method 2).

It seems there is no global namespace pollution issue (since it is inside a module) for the helper with method 1, but method 2 actually can expose some internal stuff (here the helper method) to outside through prototypal inheritance.

Any other differences (performance, etc.)? Which one should I use normally?

C.prototype.func=function(){
  // need to call helper, use either 
  // helper();
  // or
  // this.helper();
}
function helper(){// method 1
}
C.prototype.helper=function(){// method 2
}
module.exports = C;
Naeem Shaikh
  • 15,331
  • 6
  • 50
  • 88
Qiang Li
  • 10,593
  • 21
  • 77
  • 148
  • FYI, you don't define functions on the prototype like your showing. It would be `C.prototype.helper = function() {...}` – jfriend00 Dec 19 '14 at 06:29

2 Answers2

0

If you define helper() as a function inside your module, then it is different from a method in these ways:

  1. When you call helper(), the this pointer will not point to the object in question so you will not have access to member variables.
  2. helper() is not a method on the object so it can't be used that way by others.

If the function does not really operate on your object's properties and you only need it inside your module, then it makes sense to just make it a function in your module, not a method.

If you want to be able to call it from the outside world, then it must be defined elsewhere and if it is indeed operating with properties of the object, then it would be a natural to make it a public method on the object.

So, which to pick depends upon the need and situation.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

The scenarios are obvious

1)You just want to provide some functions inside the module used for other parts and don't want it be exposed to the outside, just defined a local function.

2)You want the functions be used by reference of the module, use module.prototype expose it to the outside, so you can use, modify...it.

Prototype is a very important property of javascript objects, for details you can refer to How does JavaScript .prototype work?

Community
  • 1
  • 1
sayume
  • 3
  • 2