JS creates classes and objects in two different ways

  • 2020-03-30 03:38:40
  • OfStack

In JavaScript, when you define a new function, you actually declare a new class, and the function itself is the constructor of the class. The following code shows you two different ways to create a new Person class, and the definition of person.prototype comes right after the function definition.


var Person = function(name) { //An anonymous function and assigns that function to a Person variable, where Person becomes a class

this.name = name; 

} 

function Person(name) { //Directly define a function called Person to represent the Person class

this.name = name; 

} 

Person.prototype = { //Define the prototype field for Person

printName: function() { //Define a print function

alert(this.name); 

} 

}

When you declare a class by function, you can instantiate it with the new operator. In this way, you can call the member functions of the class to complete your logic.


var person = new Person("Joe Smith"); //Use the new operator to create a new instance of Person and assign the variable Person
person.printName(); // person You can think of it as a reference to an instance (reference),  So it can be called by this reference Person Member functions in a class 

Let's summarize the entire process and steps of creating an instance of a new class:

Declare a new class by defining a function (anonymous or real-name).
2. If necessary, define the prototype field for the new class.
3. Use the new operator to create an instance of a new class immediately after the function you defined.
4. Copy all the properties and methods in the prototype field of this class into the new instance, and point all this Pointers in its member functions to the newly created instance.
5. Next, execute the function immediately following the new operator.
6. When you execute this function, if you attempt to assign a value to a nonexistent property, the JavaScript compiler will automatically create the new property for you in the instance scope.
7. When the function completes, return the initialized instance.

With the Class object in Prototype, you can declare a new object in an easy way. By using class.create (), prototype creates a default constructor for you, initialize(), and once you implement it, you can create an instance of a new Class in a similar way to a constructor in Java.


Related articles: