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.
<
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).