1

I want to know the difference between function and constructor function.

Normal function

function = dosomething(){ //do something };

Constructor Function

function = Dosomething(){ //do something };

Why we keep the first letter capital in constructor function. Is there any specific reason behind it

RobG
  • 142,382
  • 31
  • 172
  • 209
Rakesh Kumar
  • 2,705
  • 1
  • 19
  • 33
  • 1
    Aside from a few native functions, all `function`s can be used as a constructor. The naming/capitalization is just a convention used to help describe those that are explicitly intended to be used as a constructor by their author. – Jonathan Lonowski Feb 18 '14 at 04:59
  • Follow This Link [Constructor Function And Normal Function](http://stackoverflow.com/questions/8698726/constructor-function-vs-factory-functions) – Govinda Rajbhar Feb 18 '14 at 05:06
  • 1
    *"Why we keep the first letter capital in constructor function. Is there any specific reason behind it"* Probably because constructors/classes are also capitalized any many other programming languages. – Felix Kling Feb 18 '14 at 05:14
  • @RobG I was referring to native methods. [`"function slice() { [native code] } is not a constructor"`](http://jsconsole.com/?new%20Array.prototype.slice). – Jonathan Lonowski Feb 18 '14 at 05:35
  • Ok, so perhaps all native functions and built–in function Objects, but not their methods. – RobG Feb 18 '14 at 05:38
  • possible duplicate of [What are all the difference between function and constructor function in javascript?](http://stackoverflow.com/questions/22401553/what-are-all-the-difference-between-function-and-constructor-function-in-javascr) – vimal1083 Mar 31 '14 at 12:50

2 Answers2

2

There is no difference - Using the capital letter for the name is just a best practice when creating a Function that will act as a Constructor.

It's really how you treat the functions that make them behave differently. This is because Functions are first class in Javascript.

For example:

function MyRegularFunction() {
   console.log("regular");
}
MyRegularFunction();


vs.


function MyObjectFunction() {
   console.log("ctor")
}

MyObjectFunction.prototype = {
    constructor: MyObjectFunction,
    myMethod: function() {
        console.log("object")
     }
}

var myInstance = new MyObjectFunction();
myInstance.myMethod();

Hope that helps.

Newse
  • 2,330
  • 1
  • 12
  • 7
2

Capitalizing the first letter in a constructor function is just a naming convention, indicating that the function is a class. An example of a constructor function would be:

function Car(color, make, model){
    this.color = color;
    this.make = make;
    this.model = model;
}

You would then instantiate the constructor function like so:

var Dodge = new Car("Blue", "Dodge", "Caliber");
Seth
  • 10,198
  • 10
  • 45
  • 68
Marc Casavant
  • 297
  • 2
  • 11