In JavaScript, a constructor function is a special type of function that is used to create an object. It is called a constructor because it is used to construct or create objects of a particular type. Constructor functions are defined using the function
keyword and have a capitalized name by convention.
Inside the constructor function, the this
keyword is used to refer to the object that is being constructed, and properties and methods can be added to the object using dot notation. When a new object is created using the constructor function with the new
keyword, the properties and methods are automatically added to the new object.
When creating objects in JavaScript using a constructor function, we must use the new
keyword and the this
keyword to ensure that the properties are assigned to the correct instance of the object.
The new
keyword creates a new instance of the object and allows us to call the constructor function. Without using the new
keyword, the function would simply return undefined.
The this
keyword refers to the current instance of the object being created. It allows us to set the value of the properties on the current instance of the object, rather than on the constructor function itself or the global object.
<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>
<body>
<script>
function person(name, lastname, ssn) {
this.name = name;
this.lastname = lastname;
this.ssn = ssn;
}
var michael = new person("Michael", "Smith", 555444);
var samantha = new person("Samantha", "Fox", 111777);
document.write(michael.name + "<br>");
document.write(michael.lastname + "<br>");
document.write(michael.ssn + "<br>");
document.write(samantha.name + "<br>");
document.write(samantha.lastname + "<br>");
document.write(samantha.ssn + "<br>");
</script>
</body>
</html>
This code defines a constructor function called "person" which takes three parameters: "name", "lastname", and "ssn". Inside the constructor function, "this" keyword is used to refer to the new object being created by the function. The three parameters passed to the function are then assigned as properties of the new object.
The "new" keyword is used to create two new instances of the "person" object, one for Michael and one for Samantha, with their respective names, last names, and social security numbers assigned as properties.
The properties of the objects are then displayed using the document.write() function, by accessing the object's properties using the dot notation, followed by the property name.
No comments:
Post a Comment