Differences in Function Declarations in Javascript Constructor Functions

I got confused in different ways of declaring functions inside a constructor function.

function ClassName() { this.one = function() {}; var two = function() {}; three = function() {}; } 

I know that one is public and can be called externally, and two is private. What is semantics for three ?

+4
source share
3 answers

The example you provided will be a syntax error, since you need to use = for assignment in this context.

three , if used with the correct assignment operator, will be a global function that would exist outside this area. When you omit the var keyword, the variable is assigned a property of the global object, that is, window in the browser.

jsFiddle .

When using var they become VariableObject properties in the execution context. You use them as regular variables.

Further reading .

+1
source

This is the first format.

it is closer to static methods in other programming languages.

 var ClassName = { one: function() {}, two: function() {}, three: function() {} } 

Example:

  ClassName.one(); 

and the other:

 function ClassName(){ this.one = function() {}; this.two = function() {}; this.three = function() {}; } 

here you can:

 var obj = new ClassName(); obj.one(); 

In this case, you need to instantiate the object before using the methods.

These are two ways for classes in javascript ... which I know.

+1
source

These are the ones you can use in the constructor function:

 function ClassName() { // A function assigned to a property this.one = function() {}; // A function assigned to a local variable var two = function() {}; // A function declared locally function three() {} } 

Only the first ends as a member of the object.

These are the ones you can use in an object literal:

 var objectName = { // A function assigned to a property one: function() {} }; 
+1
source

All Articles