Object-Oriented Basics Summary
first day:
Understand the difference between object-oriented and process-oriented: Process-oriented is to do a problem step by step as needed. Object-oriented is to regard a problem as multiple objects, which contain attributes and methods. When necessary, write the corresponding methods and functions and call them.
Learned how to create objects: //var objectname={property or method}
var p={ //var object name={property or method}; name: "Li Si", //attribute: attribute name: attribute value; age:20, // use "," instead of ";" at the end of a property or method }
How to call the properties and methods of an object: object name.property name/method name;
①.Point syntax: object name. method name/attribute name ②[]: object name ["method name/attribute name""] can contain variables;
var p={ name:"Li Si", age:20, speak:function(){ //When the property is a function: called a method console.log("eat"); } } p.speak(); //p. method name/attribute name dot syntax console.log(p.name); console.log(p["eat"]); //p["property name/method name"] [] can be a variable (advantage)
How to add properties to objects: p. new properties or methods
for...in can be used to iterate over all properties of an object.
var p={ name:"Li Si", age:20, } p.sex="男"; //Added the sex attribute delete p.age to the object; //delete is an operator so it is not needed () console.log(p.age); // undefined is deleted for(var i in p){ console.log(i,p[i]) // Traverse the object output i: attribute name p[i]: value }
Several ways to create objects:
new Object( ) creates an object:
Disadvantages: Repeated use of an interface to create multiple objects, resulting in a lot of repetitive code.
Solution: Birth of the Factory Pattern
var p1=new Object();
p1.name="Li Si";
p1.age="20";
console.log(p); // name: "Li Si", age: 20
factory model
Solve the shortcomings of new Object( );
function p(name,age,sex){
var p1=new Object();
p1.name=name;
p1.age=age;
p1.sex=sex;
}
var p=p("Li Si",20,"Male"); //name: "李四", age: 20, sex: "男";
Disadvantages of the factory pattern: The returned values are all Objects, so the type of the object cannot be recognized;
Object created by constructor:
function Fn(name,age,sex){ //Fn constructors are generally best capitalized this.name=name; //this points to f1 from new this.age=age; this.sex=sex; } var f1=new fn("Li Si",20,"Male"); //Calling an ordinary function with new becomes a constructor. When no object is created, this points to window; console.log(f1); //name: "李四", age: 20, sex: "男";
Note: It is best not to return in the constructor, return 10; (return is invalid); return {}: return an empty object