Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor concept in javascript

In one of my questions, I got the following code as one of the answers. My understanding of the language has come has come a far better now, just have one small question.

var person = function() {
     this.firstName = "";
     this.lastName = "";
} 

person.prototype.showFullName = function () { 
     console.log(this.firstName + " " + this.lastName); 
} 

var perObj = new person();
perObj.firstName = "Penelope";
perObj.lastName = "Barrymore";
perObj.showFullName();

Considering the object,

var person = function() {
     this.firstName = "";
     this.lastName = "";
} 

and when I call this object using,

var perObj = new person();

Is this similar to constructor kind of thing?

The moment a code

var perObj = new person(); 

is invoked will the following two lines automatically get executed?

 this.firstName = "";
 this.lastName = "";

And also in one of the blogs I was studying if the file name is Samplescript.js and if a function is written using the same name inside this like var Samplescript=function(){}, will this function be considered a constructor? Please clarify me this.

I am not getting any satisfying answer regarding constructor practically even though theoretically things are clear, in this example the way its written makes lot of clear understanding.

like image 212
user5283721 Avatar asked Jan 14 '16 09:01

user5283721


People also ask

What is a constructor in JavaScript explain with an example?

In JavaScript, a constructor function is used to create objects. For example, // constructor function function Person () { this.name = 'John', this.age = 23 } // create an object const person = new Person(); Run Code. In the above example, function Person() is an object constructor function.

What is concept of constructor?

A constructor is a special method of a class or structure in object-oriented programming that initializes a newly created object of that type. Whenever an object is created, the constructor is called automatically.

Do you need a constructor in JavaScript?

Simple example no error if you don't use a constructor in the class. Constructors require the use of the new operator to create a new instance, as such invoking a class without the new operator results in an error, as it's required for the class constructor to create a new instance.


5 Answers

First of all the person is a regular JavaScript function. When you call it, of course, lines:

this.firstName = "";
this.lastName = "";

are executed. Constructor function is rather a concept than a something really existing in the JS language. You need constructors to create new similar objects by calling new MyCtr(). At the same time you need regular functions to encapsulate piece of logic and make it reusable in different places without copy/paste the code.

You can use all functions in JavaScript as a constructor. Just add new keyword in front of function call expression. This thing changes the context of execution of the function. Without new the function is executed against global object (window in a browser). And this variable inside the function refers to the context.

Not every function is ready to be a constructor. Usually, constructor functions are doing something with this variable which is a reference to an object which is created during new MyCtr() call. Also, constructor functions never return a value.

Lets look at few examples (you can execute it directly in the browser's console):

function foo() {
    this.a = 1;
}

foo();  // using function as a regular function. Ctx is window.
console.log(window.a);  // prints "1"
foo.call(window);  // explicitly specify execution ctx. The same as just foo() call

var instance = new foo();  // using foo as a constructor
console.log(instance.a);   // prints "1"

// actually you can do it without new keyword
var instance = {};  // manually create new object
foo.call(instance); // manually call foo against this object
console.log(instance.a);   // prints "1"

// However, the code above is not strictly equivalent to the code using new. 
// It omits the concept of prototype, but it's enough for our current task.

Regarding functions and files. There is no such thing in the language like in the Java that each class must be placed in the separate file. You can put all your functions within one file and then use it as constructors or not. However, the best practice is to reside one constructor function (read as class) per one file (called module).

like image 93
Ivan Velichko Avatar answered Oct 20 '22 01:10

Ivan Velichko


any function in JavaScript can act as a constructor when the function is invoked with new operator.

Now, what a constructor does ? it creates/instantiate an object from the constructor function. like its shown in the below image.

enter image description here

LINK , it explain the fundamentals very clearly.

what is this ?

when this constructor function is invoked with new, this points to the new object created at that invocation. and in that object we set firtName and lastName (it is the initialization of the new object created).

Now when we add methods to the prototype of the constructor , that is being shared between all the objects created using the constructor function(picture explains it lit bit more)

and regarding your last query "And also in one of the blogs I was studying if the file name is Samplescript.js and if a function is written using the same name inside this like var Samplescript=function(){}, will this function be considered a constructor? Please clarify me this"

any function in JavaScript can act as a constructor when the function is invoked with new operator, and its not the way that blog says.

so please stop reading that blog, the link i provided is a very good starting point

like image 41
Oxi Avatar answered Oct 20 '22 02:10

Oxi


There appear to be some holes in your understanding. Hopefully I can help.

First, the traditional conventional syntax for a constructor function is function CapitalisedFunctionName()

function Person() {
  this.firstName = "";
  this.lastName = "";
}

Note: this is not an object. From your question this isn't clear you understand that.

At this point you can add to the prototype from which all new objects created from that constructor will inherit. This modified method from your example will be available to all new objects.

Person.prototype.fullname = function () { 
  return this.firstName + " " + this.lastName;
}

Now, the constructor function allows you to create new object instances. So when you write:

var perObj = new person();

you are calling the constructor function, creating a new object instance, and assigning that instance to the perObj variable.

When you create a new object instance the object contains the firstName and lastName properties which can be accessed like so:

perObj.firstName;
perObj.lastName;

Note at the moment these have only empty strings assigned to them.

And you can call that method too:

perObj.fullname();

But, again, at this point, perObj.fullname(); won't give you anything because firstName and lastName are empty strings.

You can either define them like you have in your example: `perObj.lastName = 'Jones', or you could even change the way you create the object in the first place which is often the preferred method:

Consider this:

function Person(first, last) {
  this.firstName = first;
  this.lastName = last;
}

var perObj = new Person('Dave', 'Jones');

Now perObj will have those properties prefilled:

perObj.firstName // Dave
perObj.lastName // Jones
perObj.fullname() // Dave Jones
like image 24
Andy Avatar answered Oct 20 '22 00:10

Andy


Any function that is called with new operator acts as a constructor, so this will be assigned to the new object and points to it. Also the code inside the constructor will be executed and the new object (perObj) will get properties.

like image 27
Mehran Avatar answered Oct 20 '22 01:10

Mehran


There are a few ways to define Javascript classes and invoke them with a constructor. But remember that JavaScript is actually classless.

  1. Use a function
  2. The use of Object literals
  3. A singleton using a function

An excellent article about it can be found here: 3 ways to define a Javascript class

like image 44
Kurt Van den Branden Avatar answered Oct 20 '22 00:10

Kurt Van den Branden