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.
<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
There are a few ways to define Javascript classes and invoke them with a constructor. But remember that JavaScript is actually classless.
An excellent article about it can be found here: 3 ways to define a Javascript class
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.
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).
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.
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