Object-oriented
Introduction:
Object Oriented Programming (OOP) is a programming development idea. It abstracts all kinds of complex relations in the real world into one object, and then completes the simulation of the real world by the division and cooperation of objects. Each object is a function center, with a clear division of labor, can complete the task of receiving information, processing data, sending information and so on.
Advantage:
Flexible, code reusable, highly modular, easy to maintain and develop, more suitable for multi-person cooperation of large-scale software projects.
Characteristic:
- encapsulation
- inherit
- Polymorphism (abstraction)
Note:
Templates for creating objects in JS (ES5) are constructors, while templates for creating objects in other languages are classes.
Object instance:
<script> var dog = new Object(); dog.name = "tom"; dog.age=2; dog.color="black"; dog.eat=function(){ console.log(this.name+"Love bones") } dog.eat() </script>
Factory mode
<script> function createStudent(name,sex,age,no,){ var obj=new Object(); obj.name=name; obj.sex=sex; obj.age=age; obj.no=no; obj.test=function(){ console.log(this.name+"In the examination") } return obj; } var s1=createStudent("Zhang San","male",20,10001); var s2=createStudent("Li Si","male",25,10002); var s3=createStudent("Liu Lu","female",22,10002); s1.test(); s3.test(); console.log(s1,s2) </script>
Advantages: The ability to create objects in batches.
Disadvantage: Method will be added to every object, which will result in waste of memory.
Constructor (Template)
<script> function Student(name, sex, age, no) { this.name = name; this.sex = sex; this.age = age; this.no = no; this.test = function () { console.log(this.name + "In the examination") } } var s1 = new Student("Zhang San", "male", 20, 10001); var s2 = new Student("Li Si", "male", 25, 10002); s1.test(); console.log(s1.test==s2.test); </script>
Note:
- The constructor needs to be called using new.
- When the constructor is called by the new keyword, the system automatically creates an Object object, binds properties and methods to the object, and returns the object at the end of the call.
Mixed mode
<script> function Student(name, sex, age) { this.name = name; this.sex = sex; this.age = age; } Student.prototype.test = function () { console.log(this.name + "In the examination") }; var s1 = new Student("Xiao Ming", "male", 20); var s2 = new Student("Xiaohong", "female", 20); s1.test(); s2.test(); console.log(s1.test == s2.test); console.log(s1.__proto__.__proto__) console.log(Student.prototype.prototype) </script>
- Complete the declaration of the property in the constructor.
- The method statement is put into the prototype.
Note:
The properties and methods of prototype objects are public.
There is an attribute constructor constructor in the prototype object, and the constructor records the constructor of the object.