A daily summary of JavaScript learning (Object oriented programming) _javascript tips

Source: Internet
Author: User
Tags hasownproperty

1. Object-oriented factory approach

 function Createperson (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 person1 = Createperson ("Nicholas", "Software Engineer");
  var person2 = Createperson ("Greg", "Doctor");
  
  Person1.sayname (); "Nicholas"
  person2.sayname ()//"Greg"

The disadvantage of the factory model approach is that it produces a lot of repetitive code!

2. Constructor pattern Creation Object

 function person (name, age, Job) {
   this.name = name;
   This.age = age;
   This.job = job;
   This.sayname = function () {
    alert (this.name);}
   ;
  
  } var person1 = new Person ("Nicholas", "Software Engineer");
  var person2 = new Person ("Greg", "Doctor");
  
  Person1.sayname (); "Nicholas"
  person2.sayname ()///"Greg"
  
  alert (Person1 instanceof Object);//true
  alert (person1 instanceof person); True
  alert (Person2 instanceof Object);//true
  alert (person2 instanceof person);//true
  
  alert ( Person1.constructor = = person); True
  alert (person2.constructor = = person);//true
  
  alert (person1.sayname = = person2.sayname);//false  

Creating an object with the New keyword will go through the following four procedures

    • 1. Create a new object
    • 2. Assign the scope of the constructor to a new object (so this points to the new object)
    • 3. Methods of executing constructors (assigning values to this new object)
    • 4. Return new Object

3. Use the constructor function as a function

 function person (name, age, Job) {
   this.name = name;
   This.age = age;
   This.job = job;
   This.sayname = function () {
    alert (this.name);}
   ;
  
  } var person = new Person ("Nicholas", "Software Engineer");
  Person.sayname (); "Nicholas" Person
  
  ("Greg", "N", "Doctor");//adds to Window
  window.sayname ();//"Greg"
  
  var o = new Object ();
  Person.call (O, "Kristen", "Nurse");
  O.sayname (); "Kristen"

A constructor is used as a function without any difference to a normal function, which belongs to the method added below the Window object. Because the object created by the constructor is actually creating a new object, in essence the two are still different or separate, and their methods are not the same!

4, the common method method to solve the problem of inconsistency globally

 function person (name, age, Job) {
   this.name = name;
   This.age = age;
   This.job = job;
   This.sayname = Sayname;
  }
  
  function Sayname () {
   alert (this.name);
  }
  
  var person1 = new Person ("Nicholas", "Software Engineer");
  var person2 = new Person ("Greg", "Doctor");
  
  Person1.sayname (); "Nicholas"
  person2.sayname ()///"Greg"
  
  alert (Person1 instanceof Object);//true
  alert (person1 instanceof person); True
  alert (Person2 instanceof Object);//true
  alert (person2 instanceof person);//true
  
  alert ( Person1.constructor = = person); True
  alert (person2.constructor = = person);//true
  
  alert (person1.sayname = = person2.sayname);//true  

Although the above method solves the problem of consistency, but the definition of the global method itself belongs to window, then the local and global is not separate! So this method does not use a lot of see! It is not recommended for use.

5. Prototype mode

Any of the functions we create have a prototype object, which is a pointer to an object that can be shared by all instances of a particular type.

 function person () {
  }
  
  Person.prototype.name = "Nicholas";
  Person.prototype.age =;
  Person.prototype.job = "Software Engineer";
  Person.prototype.sayName = function () {
   alert (this.name);
  };
  
  var person1 = new Person ();
  Person1.sayname (); "Nicholas"
  
  var person2 = new Person ();
  Person2.sayname (); "Nicholas"
  
  alert (person1.sayname = = person2.sayname);//true
  
  alert (Person.prototype.isPrototypeOf ( Person1)); True
  alert (Person.prototype.isPrototypeOf (Person2));//true
  
  //only works if object.getprototypeof () Available
  if (object.getprototypeof) {
   alert (object.getprototypeof (person1) = Person.prototype);//true
   alert (object.getprototypeof (person1). name);//"Nicholas"
  }

Understanding the Prototype

Whenever you create a function, you create a prototype property that points to the prototype object of the function. By default, the prototype object will contain a constructor (constructor property) that contains a pointer to the function where the prototype property is located!

The order in which properties are read

Whenever the code reads the properties of an object, it performs a search, the target is a property of the given name, the search begins with the instance of the object itself, if it returns, and no further searches the prototype chain of the object until it finds the outermost layer of the prototype chain!

 function person () {
  }
  
  Person.prototype.name = "Nicholas";
  Person.prototype.age =;
  Person.prototype.job = "Software Engineer";
  Person.prototype.sayName = function () {
   alert (this.name);
  };
  
  var person1 = new Person ();
  var person2 = new Person ();
  
  Person1.name = "Greg";
  alert (person1.name); "Greg" comes from instance
  alert (person2.name);//"Nicholas" from prototype

If you delete an instance property of this element

function person () {
  }
  
  Person.prototype.name = "Nicholas";
  Person.prototype.age =;
  Person.prototype.job = "Software Engineer";
  Person.prototype.sayName = function () {
   alert (this.name);
  };
  
  var person1 = new Person ();
  var person2 = new Person ();
  
  Person1.name = "Greg";
  alert (person1.name); "Greg"? From instance
  alert (person2.name);//"Nicholas", from prototype
  
  delete person1.name;
  alert (person1.name); "Nicholas"-from the prototype

6, hasOwnProperty method

This method can detect whether an attribute exists in the instance or in the prototype! hasOwnProperty is inherited from object, and returns true as long as the given property exists in the object instance.

 function person () {
    }
    
    Person.prototype.name = "Nicholas";
    Person.prototype.age =;
    Person.prototype.job = "Software Engineer";
    Person.prototype.sayName = function () {
      alert (this.name);
    };
    
    var person1 = new Person ();
    var person2 = new Person ();
    
    Alert (Person1.hasownproperty ("name")); False
    alert ("name" in Person1);//true
    
    person1.name = "Greg";
    alert (person1.name);  "Greg"? From instance
    alert (Person1.hasownproperty ("name")),//true
    alert ("name" in Person1),//true
    
    alert (person2.name);  "Nicholas"? From prototype
    alert (Person2.hasownproperty ("name")),//false
    alert ("name" in Person2); True
    
    Delete person1.name;
    alert (person1.name);  "Nicholas"-from the prototype
    alert (Person1.hasownproperty ("name"),//false
    alert ("name" in Person1); /true

7, Object.keys () Enumerable property method

This method receives an object as an argument and returns an array of strings containing all enumerable properties

 function person () {
    }
    
    Person.prototype.name = "Nicholas";
    Person.prototype.age =;
    Person.prototype.job = "Software Engineer";
    Person.prototype.sayName = function () {
      alert (this.name);
    };
    
    var keys = Object.keys (Person.prototype);
    alert (keys);  "Name,age,job,sayname"
can use this method to obtain the
 function person () {
    }
    
    if it wants to get the properties of all instances, whether or not it can be enumerated. Person.prototype.name = "Nicholas";
    Person.prototype.age =;
    Person.prototype.job = "Software Engineer";
    Person.prototype.sayName = function () {
      alert (this.name);
    };
    
    var keys = object.getownpropertynames (Person.prototype);
    alert (keys);  "Constructor,name,age,job,sayname"

This method is supported by a high version browser

8, the simple prototype formulation

 function person () {
    }
    
    person.prototype = {
      name: "Nicholas",
      age:29,
      job: "Software Engineer",
      sayname:function () {
        alert (this.name);
      }
    };

    var friend = new person ();
    
    Alert (friend instanceof Object); True
    alert (friend instanceof person);//true
    alert (friend.constructor = = person);//false
    alert ( Friend.constructor = = Object); True

Rewriting a prototype is tantamount to overwriting the default prototype method, and the same construction method is overridden, and the overridden constructor points to the object! Instead of the original object person

If you still want to point to the previous construction method, you can display the specified

 function person () {
    }
    
    person.prototype = {
      Constructor:person,
      name: "Nicholas",
      age:29,
      Job: "Software Engineer",
      sayname:function () {
        alert (this.name);
      }
    ;

    var friend = new person ();
    
    Alert (friend instanceof Object); True
    alert (friend instanceof person);//true
    alert (friend.constructor = = person);//true
    alert ( Friend.constructor = = Object); False

9, the dynamic addition of the prototype method

function person () {
    }
    
    person.prototype = {
      Constructor:person,
      name: "Nicholas",
      age:29,< C24/>job: "Software Engineer",
      sayname:function () {
        alert (this.name);
      }
    ;
    
    var friend = new person ();
    
    Person.prototype.sayHi = function () {
      alert ("HI");
    };
    
    Friend.sayhi ();  "Hi"? works!

10. Prototype method of native object

Alert (typeof Array.prototype.sort);     "Function"
    alert (typeof String.prototype.substring);  "function"

    String.prototype.startsWith = function (text) {//Modify native object's prototype method return
      this.indexof (text) = = 0
    ;
    
    var msg = "Hello world!";
    Alert (Msg.startswith ("Hello"));  True

11. Create objects in combination using constructors and prototype patterns

constructor mode function person
(name, age, Job) {
      this.name = name;
      This.age = age;
      This.job = job;
      This.friends = ["Shelby", "Court"];
    }
    Prototype Mode
    Person.prototype = {
      Constructor:person,
      sayname:function () {
        alert (this.name);
      }
    };
    
    var person1 = new Person ("Nicholas", "Software Engineer");
    var person2 = new Person ("Greg", "Doctor");
    
    Person1.friends.push ("Van");
    
    alert (person1.friends);  "Shelby,court,van"
    alert (person2.friends);  "Shelby,court"
    alert (person1.friends = = person2.friends);//false
    alert (person1.sayname = = Person2.sayname); True

12. Dynamic Prototype mode

function person (name, age, Job) {
    
      //properties
      this.name = name;
      This.age = age;
      This.job = job;
      
      Methods
      if (typeof this.sayname!= "function") {
      
        Person.prototype.sayName = function () {
          alert (this.name );
        };
        
      }
    }

    var friend = new Person ("Nicholas", "Software Engineer");
    Friend.sayname ();

13. Parasitic structural function pattern

 function person (name, age, Job) {
var o = new Object ();//Rely on the global object to initialize an object and then return the object
o.name = name;
O.age = age;
O.job = job;
O.sayname = function () {
alert (this.name);
}; 
return o;
}

var friend = new Person ("Nicholas", "Software Engineer");
Friend.sayname (); "Nicholas"

function Specialarray () { 

//create the array
var values = new Array ();

Add the values
values.push.apply (values, arguments);

Assign the method
values.topipedstring = function () {return
this.join ("|");

Return it return
values; 
}

var colors = new Specialarray ("Red", "Blue", "green");
Alert (colors.topipedstring ()); "Red|blue|green"

alert (colors instanceof Specialarray);

The appeal method has a point of view, because it is dependent on the outer object to create a new object, so you cannot rely on the Instanceof method to determine the origin of the property and Method! It's actually not related to the constructor!

14, the Safe construction function pattern

 function person (name, age, Job) {
      var o = new Object ();
      O.sayname = function () {
        alert (name);
      };  
      return o;
    }
    
    var friend = person ("Nicholas", "Software Engineer");
    Friend.sayname (); "Nicholas"

This method does not rely on any new this key! If you want to access the object's methods and properties, you can only get it through the method that the object has already defined!

15. Inherit
JavaScript implementation inheritance is realized through the prototype chain

function supertype () {This.property = true;//defines a property} SuperType.prototype.getSuperValue = function () {/
    /definition of the prototype method return this.property;
    
    };
    Function subtype () {this.subproperty = false;
    
    }//inherit from Supertype subtype.prototype = new Supertype ();
    SubType.prototype.getSubValue = function () {return this.subproperty;
    
    };
    var instance = new Subtype ();  Alert (Instance.getsupervalue ());   True alert (instance instanceof Object);  True alert (instance instanceof supertype);   True alert (instance instanceof subtype);  True Alert (Object.prototype.isPrototypeOf (instance)); True Alert (SuperType.prototype.isPrototypeOf (instance));  True Alert (SubType.prototype.isPrototypeOf (instance));
 True subtype inherits Supertype methods and properties, so when instance can directly invoke the Supertype Method!
    function supertype () {this.property = true; } SuperType.prototype.getSuperValue = function () {REturn This.property;
    
    };
    Function subtype () {this.subproperty = false;
    
    }//inherit from Supertype subtype.prototype = new Supertype ();
    New Method SubType.prototype.getSubValue = function () {return this.subproperty;
    
    };
    Override existing Method SubType.prototype.getSuperValue = function () {return false;
    
    };
    var instance = new Subtype ();  Alert (Instance.getsupervalue ());

 False

The example above shows that the overridden prototype overwrites the previously inherited prototype, and the last return is often not the expected effect

 function supertype () {
      this.property = true;
    }
    
    SuperType.prototype.getSuperValue = function () {return
      this.property;
    };
    
    Function subtype () {
      this.subproperty = false;
    }
    
    Inherit from supertype
    subtype.prototype = new Supertype ();
    
    The method used to add literal amounts causes the above method to fail
    Subtype.prototype = {
      getsubvalue:function () {return
        this.subproperty;
      } ,
    
      someothermethod:function () {return
        false;
      }
    }; 
    
    var instance = new Subtype ();
    Console.log (instance);
    Alert (Instance.getsupervalue ());  error!

The following examples also illustrate the risks of rewriting prototypes

 function supertype () {
      this.colors = ["Red", "Blue", "green"];
    }

    Function subtype () {      
    }
    
    //inherit from supertype
    subtype.prototype = new Supertype ();

    var Instance1 = new subtype ();
    Instance1.colors.push ("Black");
    alert (instance1.colors);  "Red,blue,green,black"
    
    var instance2 = new subtype ();
    alert (instance2.colors);  "Red,blue,green,black"

Prototype sharing the same data that caused two different objects to invoke
16, the use of constructors to achieve inheritance

 function supertype () {
      this.colors = ["Red", "Blue", "green"];
    }

    Function subtype () { 
      //inherit from supertype
      Supertype.call (this);
    }

    var Instance1 = new subtype ();
    Instance1.colors.push ("Black");
    alert (instance1.colors);  "Red,blue,green,black"
    
    var instance2 = new subtype ();
    alert (instance2.colors);  "Red,blue,green"

Passing parameters

 function Supertype (name) {
      this.name = name;
    }

    Function subtype () { 
      //inherit from supertype passing
      to argument Supertype.call (this, "Nicholas");
      
      Instance Property
      This.age =

    var instance = new Subtype ();
    alert (instance.name);  "Nicholas";
    alert (instance.age);   29

17. Combined Inheritance Mode

function Supertype (name) {
      this.name = name;
      This.colors = ["Red", "Blue", "green"];
    }
    
    SuperType.prototype.sayName = function () {
      alert (this.name);
    };

    Function subtype (name, age) { 
      Supertype.call (this, name);
      
      This.age = age;
    }

18. Prototype Inheritance

 function Object (o) {
      function F () {}
      f.prototype = O;
      return new F ();
    }
    
    var person = {
      Name: "Nicholas",
      friends: ["Shelby", "Court", "Van"]
    };
    
    var Anotherperson = object (person);
    Anotherperson.name = "Greg";
    AnotherPerson.friends.push ("Rob");

19, parasitic modular inheritance

 function Object (o) {function F () {} f.prototype = O;
    return new F ();  function Inheritprototype (subtype, supertype) {var prototype = object (Supertype.prototype);        Create Object prototype.constructor = subtype;         Augment object subtype.prototype = prototype;
      Assign object} function supertype (name) {this.name = name;
    This.colors = ["Red", "Blue", "green"];
    } SuperType.prototype.sayName = function () {alert (this.name);

    };
      
      Function subtype (name, age) {Supertype.call (this, name);
    This.age = age;
    
    } inheritprototype (subtype, supertype);
    SubType.prototype.sayAge = function () {alert (this.age);
    
    };
    var Instance1 = new Subtype ("Nicholas", 29);
    Instance1.colors.push ("Black"); alert (instance1.colors);   "Red,blue,green,black" Instance1.sayname ();
    "Nicholas";    Instance1.sayage ();
    
  29  
    var instance2 = new Subtype ("Greg", 27); alert (instance2.colors);   "Red,blue,green" Instance2.sayname ();
    "Greg";    Instance2.sayage ();
 27

Above is today's JavaScript learning Summary, and will continue to update every day, I hope you continue to pay attention.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.