Summary of several usages of the inheritance in JS

Source: Internet
Author: User
Tags inheritance ming

  This article mainly introduces the several usage summary of the inheritance in JS (Apply,call,prototype) The friend that needs can come over the reference, hope to be helpful to everybody

One, JS in object inheritance   JS three inheritance methods   1.js prototype (prototype) implementation of inheritance   code as follows: <span style= "Background-color: #ffffff" > <span style= "font-size:18px" ><html>   <body>   <script type= "Text/javascript" >       function person (name,age) {          this.name=name;       &N Bsp   This.age=age;      }       person.prototype.sayhello=function () {          Alert ("Use prototype to get Name:" +this.name);      }       var per=new person ("Ma Xiao", 21);       Per.sayhello (); Output: Using prototypes to get Name: Ma Xiao                function Student () {}       Stude Nt.prototype=new person ("Hongru", 21);       var stu=new Student ();       student.prototype.grade=5;       Student.prototype.intr=function () {          alert (this.grade); &nBsp    }       Stu.sayhello ()//output: Using prototype to get Name: Hongru       STU.INTR ();//output: 5   < /script>   </body>   </html></SPAN></SPAN>     2. Constructor implementation inheritance code is as follows: <span Style= "font-size:18px" ><html>   <body>   <script type= "Text/javascript" >       function  parent (name) {          This.name=name;           This.sayparent=function () {              alert ("Parent:" +this.name);           {     }         function  child (name,age) {&N Bsp         this.tempmethod=parent;           This.tempmethod (name);           this.age=age;           this.saychild=function () {              alert ("Child: "+this.name+" Age: "+this.age";           {     }         var parent=new parent ("Jiang Jiansen");       parent.sayparent (); Output: "Parent: Jiang Jiansen"       var child=new child ("Li Ming", 24); Output: "Child: Li Ming age:24"       child.saychild ();   </script>   </body>   </html></SPAN>    3.call, apply implementation inheritance code as follows: <s PAN style= "font-size:18px" ><html>   <body>   <script type= "Text/javascript" >   & nbsp   function  person (name,age,love) {          This.name=name;       &NBSP ;   This.age=age;           This.love=love;           this.say=function say () {              alert ("Name:" +n AME);           {     }        //call mode      function Student (name,age) {          Person.call (this,name,age);      } & nbsp      //apply mode       function teacher (name,love) {          person . Apply (This,[name,love]);          //person.apply (this,arguments); The same effect as the previous sentence, arguments      }        //call and aplly:      //1, first parameter thi s all the same, refers to the current object      //2, the second parameter is different: Call is a list of parameters; Apply is an array (arguments also can)         var Per=new person ("Wu Feng Building", 25, "Wei Screen"); Output: "Wu Feng Building"       Per.say ();       VAR stu=new student ("Cao Yu", 18);//output: "Cao Yu"       Stu.say ();       var tea=new teacher ("Qin Jie", 16);//output: "Qin Jie"       Tea.say ();     </script>   </body>   </html></SPAN>     II Call and apply usage (detailed)   JS call and apply can be implemented, the only point of different parameters, Func.call (FUNC1,VAR1,VAR2,VAR3) The corresponding apply is written as: Func.apply (FUNC1,[VAR1,VAR2,VAR3)).   JS Manual explanation of call:     code as follows: <span style= "font-size:18px" >call method   invokes one method of an object, replacing the current object with another object.         Call ([thisobj[,arg1[, arg2[,   [,. Argn]]]]]-    parameter   thisobj   optional. The object that will be used as the current object.     Arg1, arg2,  , argn   optional. A sequence of method parameters is passed.     Description   Call method can be used to invoke a method instead of another object. The call method can change the object context of a function from the initial context to the new object specified by Thisobj.     If the thisobj parameter is not supplied, the Global object is used as a thisobj. </SPAN>     To put it simply, the function of these two functions is to change the object's internal pointer, that is, to change the object's this point. This is sometimes useful in the object-oriented JS programming process. The following takes apply as an example, say these two functions in JS important role. For example: Copy code code as follows: <span style= "font-size:18px" > Function person (name,age) { //define a class        &N Bsp   This.name=name;    //name            this.age=age;      //Age            this.sayhello=function () {alert (this.name)};      }       function Print () {           //Display class properties  &nbs P         this.funcname= "Print";           this.show=function () {              var msg=[] &nbs P             for (var key in this) {                &N Bsp if (typeof (This[key])!= "function") {                      Msg.push ([ Key, ":", This[key]].join (""));                   {             }               alert (Msg.join (""));          };      }       function Student (name,age,grade,school) {   //student class    &nbsp ;       person.apply (this,arguments)//More advantageous place than call            print.apply (this,arguments);           This.grade=grade;                //grade            This.school=school;                //school        {      var p1=new Person ("Bu culture", 80);       P1.sayhello ();       var s1=new Student ("Baiyunfei", 40, 9, "Yuelu Academy");       s1.show ();       S1.sayhello ();       alert (s1.funcname);</span>     In addition, function.apply () has a prominent role in improving program performance: We start with Math.max () function, Math.max can be followed by any parameter, and finally returns the maximum value in all parameters. For example, the code is as follows: <span style= "font-size:18px" >alert (Math.max (5,8));  //8        alert (Math.max (5,7,9,3,1,6));  //9         //But in many cases, we need to find the largest element in the array.          var arr=[5,7,9,1];      //alert (Math.max) (ARR));    //But that's not going to work. NaN         //To write        function Getmax (arr) {          VAR arrlen=arr.length;           for (Var i=0,ret=arr[0];i<arrlen;i++) {            &NBS P Ret=math.max (Ret,arr[i]);           {          return ret;      }         alert (Getmax (arr)); 9         //exchange apply, you can write        function getMax2 (arr) {    &nbs P     return Math.max.apply (Null,arr);      }         alert (GETMAX2 (arr)); 9         //Two code achieves the same goal, but GETMAX2 is elegant, efficient, and much simpler.         /or the push method for arrays.        var arr1=[1,3,4];       var arr2=[3,4,5];      //If we want to expand the arr2, then one by one append to the arr1, and finally let arr1=[1,3,4,3,4,5]       //arr1.push (ARR2) is obviously not going to work. Because doing so will get [1,3,4,[3,4,5]]         //We can only use one loop to go one push (of course, we could also use Arr1.concat (ARR2), But the concat method does not change arr1 itself)          var arrlen=arr2.length;       for (Var i=0;i<arrlen;i++) {          Arr1.push (Arr2[i]);     &N Bsp        //Ever since the apply, things have become so simple          Array.prototype.push.apply (arr1, ARR2); Now ARR1 is the result of the want </SPAN>  

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.