A summary of javascript learning every day (Object-Oriented Programming) _ javascript skills

Source: Internet
Author: User
Tags hasownproperty
This article mainly introduces the knowledge points of object-oriented programming in javascript, outlines object-oriented programming, and sorts out various methods. If you are interested, you can refer 1. Object-oriented factory Method

 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", 29, "Software Engineer");  var person2 = createPerson("Greg", 27, "Doctor");    person1.sayName(); //"Nicholas"  person2.sayName(); //"Greg"

The disadvantage of the factory model method is that it will produce a large number of repeated code!

2. Create an object in the constructor Mode

 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", 29, "Software Engineer");  var person2 = new Person("Greg", 27, "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  

Using the new keyword to create an object will go through the following four processes:

  • 1. Create a new object
  • 2. Assign the scope of the constructor to a new object (so this points to this new object)
  • 3. Method for executing the constructor (assign a value to this new object)
  • 4. Return the new object

3. Use constructor 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", 29, "Software Engineer");  person.sayName(); //"Nicholas"    Person("Greg", 27, "Doctor"); //adds to window  window.sayName(); //"Greg"    var o = new Object();  Person.call(o, "Kristen", 25, "Nurse");  o.sayName(); //"Kristen"

If you use a constructor as a function, it is no different from a common function. It belongs to the method added under the window object. Because the object created by the constructor is actually creating a new object, the two are essentially different. They are still separated and their methods are still different!

4. Global Solution for inconsistency

 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", 29, "Software Engineer");  var person2 = new Person("Greg", 27, "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 consistency problem, but the defined global method itself belongs to the window, the local and global are not separated! So this method is rare! It is not recommended.

5. Prototype

Any function we create has a prototype object, which is a pointer pointing to an object, this object can be used to share all instances of a specific type!

 function Person(){  }    Person.prototype.name = "Nicholas";  Person.prototype.age = 29;  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() is available  if (Object.getPrototypeOf){   alert(Object.getPrototypeOf(person1) == Person.prototype); //true   alert(Object.getPrototypeOf(person1).name); //"Nicholas"  }

Understanding prototype

Whenever a function is created, a prototype attribute is created, which points to the prototype object of the function. By default, the prototype object will contain a constructor (constructor attribute), which contains a pointer to the function of the prototype attribute!

Order of attribute reading

Every time the Code reads the attributes of an object, it performs a search. The target is an attribute with a given name. The search starts from the instance of the object. If yes, it returns, if no, search for the prototype chain of the object until the outermost layer of the prototype chain is found!

Function Person () {} Person. prototype. name = "Nicolas"; Person. prototype. age = 29; 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); // "Nicolas" from prototype

If the instance attribute of this element is deleted

function Person(){  }    Person.prototype.name = "Nicholas";  Person.prototype.age = 29;  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 a property exists in the instance or in the prototype! HasOwnProperty is inherited from the Object. If the specified property exists in the Object instance, true is returned.

 function Person(){    }        Person.prototype.name = "Nicholas";    Person.prototype.age = 29;    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 () Enumeration property Method

This method receives an object as a parameter and returns an array of strings containing all the enumerated attributes.

Function Person () {} Person. prototype. name = "Nicolas"; Person. prototype. age = 29; Person. prototype. job = "Software Engineer"; Person. prototype. sayName = function () {alert (this. name) ;}; var keys = Object. keys (Person. prototype); alert (keys); // "name, age, job, sayName" if you want to get the attributes of all instances, whether it can be enumerated or not, you can use this method to obtain function Person () {} Person. prototype. name = "Nicolas"; Person. prototype. age = 29; 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 browsers of higher versions.

8. Simple prototype writing

 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

If the prototype is rewritten, the default prototype method is overwritten. The same constructor method is overwritten. The rewritten constructor points to the Object! Instead of the original object Person

If you still want to point to the previous constructor method, you can specify

 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. Dynamic addition of prototype Methods

function Person(){    }        Person.prototype = {      constructor: Person,      name : "Nicholas",      age : 29,      job : "Software Engineer",      sayName : function () {        alert(this.name);      }    };        var friend = new Person();        Person.prototype.sayHi = function(){      alert("hi");    };        friend.sayHi();  //"hi" ?works!

10. Native object Prototype Method

Alert (typeof Array. prototype. sort); // "function" alert (typeof String. prototype. substring); // "function" String. prototype. startsWith = function (text) {// modify the native object's prototype method return this. indexOf (text) = 0 ;}; var msg = "Hello world! "; Alert (msg. startsWith (" Hello "); // true

11. Create objects using constructor and prototype

// Constructor mode function Person (name, age, job) {this. name = name; this. age = age; this. job = job; this. friends = ["Shelby", "Court"];} // prototype: Person. prototype = {constructor: Person, sayName: function () {alert (this. name) ;}}; var person1 = new Person ("Nicolas", 29, "Software Engineer"); var person2 = new Person ("Greg", 27, "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

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", 29, "Software Engineer");    friend.sayName();

13. Parasitic constructor Mode

Function Person (name, age, job) {var o = new Object (); // depends on the global Object to initialize an Object, and then returns this Object o. name = name; o. age = age; o. job = job; o. sayName = function () {alert (this. name) ;}; return o ;}var friend = new Person ("Nicolas", 29, "Software Engineer"); friend. sayName (); // "Nicolas" function SpecialArray () {// create the arrayvar values = new Array (); // add the valuesvalues. push. apply (values, arguments); // assign the methodvalues. toPipedString = function () {return this. join ("|") ;}; // return itreturn values;} var colors = new SpecialArray ("red", "blue", "green"); alert (colors. toPipedString (); // "red | blue | green" alert (colors instanceof SpecialArray );

The appeal method indicates that, because it depends on the outer object to create a new object, it cannot rely on the instanceof method to determine the source of attributes and methods! It actually has nothing to do with the constructor!

14. Robust constructor Mode

 function Person(name, age, job){      var o = new Object();      o.sayName = function(){        alert(name);      };        return o;    }        var friend = Person("Nicholas", 29, "Software Engineer");    friend.sayName(); //"Nicholas"

This method does not depend on any new this key character! If you want to access the methods and attributes of an object, you can only obtain them through the methods defined by the object!

15. Inheritance
Javascript implementation inheritance is implemented through the prototype chain.

Function SuperType () {this. property = true; // defines an attribute} SuperType. prototype. getSuperValue = function () {// defined 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 (instan Ce 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); // trueSubType inherits the SuperType method and attributes, so when the instance can directly call 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 preceding example shows that the rewritten prototype overwrites the previous inherited prototype, and the final returned result is often not the expected result.

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 SubType is invalid due to the method added using the literal. prototype = {getSubValue: function () {return this. subproperty ;}, someOtherMethod: function () {return false ;}}; var instance = new Sub Type (); console. log (instance); alert (instance. getSuperValue (); // error!

The following examples also illustrate the risks caused by prototype rewriting.

 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 causes two different objects to call the same data.
16. Use constructors to implement 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"

PASS Parameters

 function SuperType(name){      this.name = name;    }    function SubType(){       //inherit from SuperType passing in an argument      SuperType.call(this, "Nicholas");            //instance property      this.age = 29;    }    var instance = new SubType();    alert(instance.name);  //"Nicholas";    alert(instance.age);   //29

17. Combination inheritance

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 combined 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

The above is the summary of today's javascript learning, and will be updated every day. I hope you will continue to pay attention to it.

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.