This is the 14th day of my participation in Gwen Challenge
The constructor
Constructors are another way to create objects in JS. Constructors can create objects with the same characteristics as those created by the literal “{}”. That’s why we use constructors to create objects when we have a flexible way of creating objects with literals.
JavaScript built-in constructors
JavaScript provides constructors such as Object, String, Number, etc. How do we use and? The creation of an object using the new keyword is often referred to as the instantiation process, and the instantiated object becomes an instance of the constructor.
Here’s an example:
Var o1 = new Object(); var o2 = new String("JavaScript"); var o3 = new Number(100); Console. log(o1.constructor); // Check which constructor the object is created by. console.log(o2.constructor); console.log(o3.constructor); </script>Copy the code
Custom constructors
In addition to the built-in constructors in JS, users can also customize constructors. Note the following two rules:
- It is recommended that all words be capitalized using the PASCAL naming rule
- Use this inside the constructor to represent the object you just created.
Let’s see how to customize the constructor:
Function Person(name,age){this.name = name; this.age = age; This.speak = function(){console.log(" I "+this.name); }; } person1 = new Person(' Java ',10); var person2 = new Person('Maria',20); // Output object console.log(person1); console.log(person2); // Call the object's method person1.speak(); person2.speak(); </script>Copy the code
Class keyword added in ES6
The use of the class keyword is common in various object-oriented programming languages, and JavaScript has added the class keyword to make life easier for developers.
<script> class Person{ constructor (name,age,gender){ this.name = name; this.age = age; this.gender = gender; } speak(){console.log(" I am "+this.name); } } var person = new Person('jack',19,'man'); person.speak(); </script>Copy the code