Object-oriented Programming (OO)

Recently feeling, don’t know what to learn, always feel oneself what all can’t, what feeling is to be able to point, also know object oriented, but the system said these things, feel even not online, become a mt system, so I took a look at this knowledge, when their handlers, pretending to be an article, such as his view is convenient;

Create an object

1. Factory pattern: Encapsulate functions to create details of objects with specific interfaces

  1. Solved the problem of creating multiple similar objects,
  2. Used to create multiple objects containing the same properties, and methods, to avoid repeated code writing;
  3. Does not solve the Object recognition problem (how to know the type of an Object) (its instanceof can only be Object)
   function creatPerson(name,age,job) {
        var o = new Object();
        o.name= name;
        o.age= age;
        o.job= job;
        o.sayName = function(){
            alert(this.name);
        };
        return o;
    }
    var p1 = creatPerson("hh", 23,"worker");
    var p2 = creatPerson("xx", 26,"worker1"); p1.__proto__===p2.__proto__===Object.prototype; The constructor property of the Object was originally used to describe formation types, detecting Object types as well as objects created by the more reliable Instanceof factory pattern. The constructor property has only Object, such instances have no specific type;Copy the code

2. Constructor mode:

  1. Solve the problem of object recognition (how to know the type of an object)
  2. Disadvantages: Each method is recreated on each instance, p1.sayName! =p2.sayName
  3. Solution: propose the constructor, in the global write a function declaration; (The disadvantage of this solution is that global functions are only called locally, and too many methods require the creation of multiple global functions, so there is no encapsulation);
    function Person(name,age,job){
        this.age = age;
        this.name = name;
        this.job = job;
        this.sayName = function(){ alert(this.name) } //this.sayName = sayName; } var p1 = new Person("hh", 23,"worker");
    var p2 = new Person("xx", 26,"worker1");
        
        //function sayName(){alert(this.name)} // Implement new: {var obj ={}; obj.__proto__ = Person.prototype; Person.call(obj);return obj
        }
    p1 instanceof Person //true;
    p2 instanceof Person //true;
    p1 instanceof Object //true;
    p2 instanceof Object //true; So p1 and P2 instances have a specific type, Person;Copy the code

3. Prototyping

  1. Advantages: It omits constructor initialization parameters, all attributes in the prototype are shared by many instances, sharing is very suitable for the function, basic attributes are also ok by adding the same attribute on the instance, can hide the corresponding attribute value in the prototype;

  2. Disadvantages: The shared attribute has no effect on the property containing the reference type value if the instance is reassigned, as with the basic type, there is a problem with the operation modification, which will cause all instances of the property to be modified, so it is not used alone

        function Person(){}
        Person.prototype={
            constructor:Person,
            name:"ss",
            friends:["s1"."s2"],
            sayName:function(){alert(this.name)}
        }
        var p1= new Person();
        var p2= new Person();
        p1.name = "p1"
        console.log(p1.name) //p1
        console.log(p2.name) //ss
        p1.friends.push("s3");
        console.log(p1.friends) //["s1"."s2"."s3"]
        console.log(p2.friends) //["s1"."s2"."s3"]
    Copy the code
  3. Usage:

    1. General usage:
          function Person(){}
          Person.prototype.name="ceshi"
          Person.prototype.age =12;
          Person.prototype.sayName = function(){alert(this.name)} // This implements code sharingCopy the code
    2. Simple notation
      Prototype ={//constructor:Person, name:"test",
                  age:12,
                  sayName:function(){alert(this.name)}
              }
          var friend = new Person();
          friend instanceof Object //true
          friend instanceof Person //true
          friend.constructor==Person //false
          friend.constructor==Object //trueThis simple way of writing the constructor property points not to a Person but to an Object constructor; Add a property constructor(as noted above) : But the constructor becomes an enumerable property, and the native property is not enumerable. Consider object.defineProperty () instead.Copy the code
    3. Prototype dynamics:
      var p1 = new Person(); <! -- 1 --> Person.prototype.hh="ss"; P1.hh //ss is accessible by creating an instance before changing the edge of the prototype; <! -- 2 --> Person.prototype={ name:"ss"} p1.__proto__! =Person.prototype; p1.name // undefinedCopy the code
    4. Prototypes for native objects:
      1. Native reference types (Object, Array, String…) can be assigned Add modification method String. Prototype. StrarWith = function (tesx) {return enclosing indexOf (text) = = 0}

4. Use a combination of constructor pattern and stereotype pattern :(a default pattern for defining reference types)

  1. The constructor pattern is used to define instance properties; Each attribute is recreated on each instance; Even changes to reference types do not affect other instances
  2. The stereotype pattern is used to define methods and shared properties;
    functionPerson(age,name){ this.name = name; this.age = age; Constructor ={constructor:Person, sayName: Person, sayName: Person, sayName: Person, sayName: Person, sayName: Person, sayName: Personfunction(){
            alert(this.name)
        }
    }
    var p1 = new Person("ss", 12); var p2 = new Person("ss3", 123); p1.friends.push(2); The console. The log (p1. Friends) / /,2,3,2 [1] the console. The log (p2) friends) / / [1, 2, 3]Copy the code

5. Dynamic prototype mode:

  1. Prototypes are separate from paparazzi functions and feel different from OO in other languages. Dynamic prototypes encapsulate all information in constructors.
  2. To initialize a prototype, check whether a method that should be initialized is valid in the constructor

    function Person(name,age){
        this.name = name;
        this.age = age;
        if(typeof this.sayName ! ="function"SayName = person.prototype.sayName = person.prototype.sayname = person.prototype.sayname = person.prototype.sayname = person.prototype.sayname = person.prototype.sayname =function(){alert(this.name)}
            Person.prototype.sayAge=function(){alert(this.age)}; . } **** note **** : this method cannot be used to rewrite the prototype in the form of object literals, because this method is first created in the instance, and then modified in the prototype. If you use object literals to rewrite the prototype, the connection between the existing instance and the new prototype will be cut off, resulting in no method on the method instance; }Copy the code

6. Parasitic constructor mode:

  1. Similar to factory mode, but with new initialization instance;
  2. The object it returns has nothing to do with the constructor and its prototype;
    function Person(name,age){
        var o = new Object();
        o.name=name;
        o.age=age;
        o.sayName=function(){
            alert(this.name)
        };
        return o;
    }
    var friends = new Person("xiaoming",12)
    friends.asyName()  // xiaoming

Copy the code

7. Safe constructor mode:

Secure object: an object that has no public properties and does not reference this in its methods;

function Person(name,age){
        var o = new Object();
        o.sayName=function(){
            alert(name)
        };
        return o;
    }
    var friends = new Person("xiaoming",12)
    friends.asyName()  // xiaoming
Copy the code

Inheritance:

  1. Inheritance generally includes: interface inheritance: inheriting methods and signatures; Implementation inheritance: Inherits the actual method; ECMAScript only supports implementation inheritance

  2. Js inheritance is implemented primarily through a prototype chain, which is constructed by assigning an instance of a type to a prototype of another constructor

Inheritance way

1. Prototype chain (rarely used alone)
  1. Problem: Data that operates on a reference type (reassignment does not affect, as subclasses add hidden parent classes) is shared by all instances
  2. Problem er: Cannot pass arguments to the parent constructor when creating a subclass; ?????
Son.prototype = new Father(); // Son.constructor = Father; Son.prototype.constructor = Son; Son.prototype.getname = son.prototype.getName = son.prototype.getName = son.prototype.getName = son.prototype.getName = son.prototype.getName = son.prototype.getName = son.prototype.getNamefunction(){alert(this.name)};

Copy the code
2. Constructor binding: call,apply inheritance: (rarely used alone)
  1. Problem: methods in the parent function prototype are not subclassed
  2. QTL: Method properties are defined in constructors, and each instance and method is recreated, without reuse
    function Son(){
        Father.call(this,arguments)
    }
Copy the code
3. Composite inheritance :(common inheritance pattern)
  1. This allows instances to have separate attributes (including reference type, inter-instance complementary effects) and to use the same approach;
  2. Pitfalls: In any case, the parent class’s constructor is called twice;
    function Father(){
        this.name ="ss"; This. Friends = [1, 2, 3, 4]}function Son(){ Father.call(this); } Son.prototype = new Father(); Var son1 = new Son(); var son1 = new Son(); // Call the Son constructor to add attributes (name and friends) to the son1 instance. These attributes mask the same attributes in the prototype; // The result of calling the Father constructor twice is two sets of attributes, one on the instance and one on the prototype;Copy the code
4. Original type inheritance:
  1. In cases where there is no need to create a constructor, but just want one object to be similar to another, it can be used, like money copy;
    function object(o){
        function F() {}; F.prototype = o;returnnew F(); } // Same as when object.creat () passes a parameterCopy the code
5. Parasitic inheritance:
  1. Inheriting origin’s properties and methods;
  2. At the same time, it has its own method;
    function creat(origin){
        var clone= object(origin); // It can be any function that returns a new object.sayName(){alert("name")}; // The function is created every time, so there is no reuse.return clone;
    }
Copy the code
6. Parasitic combination :(ideal inheritance implementation)
  1. Solve defects in combinatorial inheritance, generate two sets of properties, and generate prototypes only on instances;
  2. Inheriting properties through constructors, inheriting methods through a mashup of prototype chains.
    functioninherit(son,father){ var prototype = object(father.prototype); Prototype.__proto__ = Father. Prototype; / / prototype inheritance constructor prototype. Take the constructor's prototype chain, the Father of prototype. The prototype. The constructor, as the Father (); Constructor == prototype.__proto__. Constructor //true
            // prototype.hasOwnPrototyoe("constructor") / /falseprototype.constructor = son; // make up for default property changes caused by overwriting the stereotype; / / at this point is added a constructor properties to the prototype, the assignment for son, shielding the constructor property on the prototype / / prototype hasOwnPrototype ("constructor") / /true// prototype.constructor = son; // prototype.__proto__.constructor = father son.prototype = prototype; // Assign the subclass stereotype to a copy of the parent stereotype; } // use:function Father(){
        this.name="11";
        this.age=12;
    }
    Father.prototype.sayName=function(){
        alert(this.name);
    }
    function Son(){
        Father.call(this);
        this.age=23;
    }
    inherit(Son,Father);
    Son.prototype.sayAge=function(){
        alert(this.age)
    }

Copy the code