Create a class
- Creating a class in JavaScript is easy by first declaring a function to be stored in a variable. It is customary to capitalize the variable name representing the class. Add a property or method to the function (class) by adding a property or method to the this variable (this is a built-in variable that points to the current object), for example:
let Book = function (id, bookName, bookPrice){
this.id = id;
this.bookName = bookName;
this.bookPrice = bookPrice;
}
let book = new Book(1, "JavaScript Design Patterns"."39");
console.log(book.id,book.bookName,book.bookPrice)
Copy the code
- You can also add properties and methods to the prototype of the class by assigning values to the properties of the prototype object or assigning an object to the prototype object. But don’t mix the two. For example:
Book.prototype.booktype = // The prototype object attribute is assigned to book.prototype.bookType =function (code){
console.log(code)
console.log('If I call the person method, I'll get this line of logic right here.')
}
book.bookType('front end')
Copy the code
// Assign an object to the class's prototype object. Prototype = {person:function (person) {
console.log(person)
console.log('If I call the person method, I'll get this line of logic right here.')
}
}
book.person('wzy');
Copy the code
- So we encapsulate all the methods and properties we need in our abstract Book class. When using the eject method, we can’t use the Book class directly. We need to use the new keyword to instantiate (create) the new object. Properties or methods of instantiated objects can be accessed through point syntax.
How are the properties and methods added by this different from those added by Prototype?
- Adding attributes and methods through this is done on the current object, but JavaScript is a prototype-based language, so every time you create an object (and of course functions are objects in JavaScript), It all has a prototype that points to inherited properties and methods. Methods inherited from Prototype are not objects themselves, so when using them you need to look them up through Prototype level by level. So every time we create a new object from a class, the properties and methods referred to by this will be created accordingly. The properties and methods inherited from Prototype will be accessed by each object in Prototype. So every time we create a new object from a class these properties and methods are not created again.
- Constructor is a constructor property. When a function or object is created, a prototype object is created for it. A constructor property is created in the prototype object just as this is created in the function. The constructor property points to the function or object that owns the prototype object. For example, the constructor property in book. prototype points to the Book class object.