Object-oriented three major features: encapsulation, inheritance, polymorphism.
1. Original Modevar obj = new Object (); Obj.name = name; Obj.sex = Sex;obj.showname = function () {alert ("My name is" +this.name)}obj.showsex ... var Cat = {} can also Create the same principle in JSON mode
2. Factory modeEasy-to-understand version of function Createperson (name,sex) {//raw var obj = new Object (); Processing obj.name = name; Obj.sex = sex; Obj.showname= function () {alert (' My name is ' +this.name '); }//Factory}json version function Cat (name,color) {return {name:name, Color:color, Shownamr:func tion () {alert (' My name is ' +this.name '); }}} Cons: No new, multiple copies created, code not concise
3. Constructor Modefunction Cat (name,color) {this.name = name; This.color = color;} var cat1 = new Cat ("Elephant", "yellow Hair"); The role of new: 1. The system automatically creates an object 2. Point the internal this to the created Object 3. Return This object disadvantage: Create multiple replicas still waste memory resources
4. Prototype mode (mixed method)
function Cat (name,colot) {
this.name = name;This.color = color;
}Cat.prototype.type = "Cat animal"; Cat.prototype.eat = function () {alert ("Eat Mouse");} Note alert (cat1.eat = = cat2.eat); TrueType and eat point to the same piece of memory area the cat is the class is also the constructor in JS is part of the structure of the home of the initial capitalization of the method attributes and the method property of the instance between the two lines the higher precedence replaces the method property on the prototype
5. Commonly used methods for object-orientedThe prototype property gives you the ability to add properties and methods to an object (that is, a method of a class in Java) constructor: Returns a reference to the function that this object created (constructor) Instanceof: The object is not an instance of a constructor isPrototypeOf () determines the relationship between the prototype object and the instance Cat.prototype.isPrototypeOf (CAT1); hasOwnProperty () determines whether the property is an inline local property or Integrated Prototypecat1.hasownproperty (' name ') belongs to itself return Truein determine whether to include a property, whether local or prototype "name" in cat1in used to traverse all properties
The evolution and common methods of JS object-oriented realization method