Javascript Constructor functions
In JavaScript, instances—also known as objects of a particular type—are created using a function Object() { [native code] } function. The function Object() { [native code] } function is used to specify the instances’ properties and methods. The function Object() { [native code] } function is defined using the function keyword, and to identify it as such, its name should start with a capital letter.
Example:
function Person(name, age) {
this.name = name;
this.age = age;
this.sayHello = function() {
console.log("Hello, my name is " + this.name);
}
}
The Person function Object() { [native code] } function in this example specifies two attributes on each instance created by the function Object() { [native code] }: name and age. It accepts two inputs, name and age. Additionally, it defines a sayHello method that uses the name property to log a message to the console.
Use the new keyword to make an instance of the Person object:
var john = new Person("John", 30);
john.sayHello(); // logs "Hello, my name is John"
This example creates a new Person object with the name “John” and the age of 30. Then, the john object’s sayHello method is invoked, which prints “Hello, my name is John” to the console.
In JavaScript, function Object() { [native code] } functions are used to construct objects of any type and can have any quantity of properties and methods.