Home > Article > Web Front-end > A brief discussion on the simulation of object-oriented technology in JavaScript_javascript skills
1. Introduction
In C# and Java languages, object-oriented is implemented in the form of classes, especially inheritance. Class inheritance shows powerful functions and is easy to learn. JavaScript is not a pure object-oriented language, but an object-based language. The inheritance of objects is in the form of prototype functions. Many beginners do not understand it when they first come into contact with it, but JavaScript is implemented in the form of prototype functions. Object-oriented technology is not only feasible, but also provides dynamic inheritance functions for object-oriented technology. This article mainly discusses the object-oriented technology of JavaScript.
2. Overview of prototype objects
Every JavaScript object has a prototype object, and the objects inherit all properties of the prototype object. An object's prototype is defined by the constructor that creates the object. All functions in JavaScript have an attribute called prototype, which refers to the prototype object. When the prototype object is initialized, only the constructor attribute refers to the object that created the prototype object. JavaScript does not have the concept of Class to define a class. The constructor defines the class and initializes the properties in the class. The members of each class will inherit the same properties from the prototype object. In other words, the prototype object provides the same properties shared by instances of the class. Properties and methods, which saves memory.
When reading the properties of an object, JavaScript will first search from the object. If it is not found, it will search for the property (or method) in the prototype object. Therefore, especially for methods, it is best to save them. into the prototype object to facilitate sharing and save memory, and the prototype object also has a powerful function, that is, if you instantiate some objects through the constructor, and then add attributes and methods to the prototype object of the constructor, then The object instance it originally instantiated will inherit these added properties and methods.
3. Object attributes, object methods, class attributes, class methods
Each object will have its own separate copy of instance attributes and instance methods. If 5 objects are instantiated, there will be 5 objects. Copies of instance properties and instance methods. This keyword refers to their instance objects, that is to say, whoever operates the instance method, this refers to him; which instance object attribute is accessed, this refers to the instance object.
There is only one copy of class methods and class attributes. When calling a class method, the name of the class must be quoted, for example: Date.setHours();
A program is used below to represent instance attributes, instance methods, class attributes, and classes. Method