zoukankan      html  css  js  c++  java
  • js继承的三种实现

    概念:在有些面向对象语言中,可以使用一个类(子类)继承另一个类(父类),子类可以拥有父类的属性和方法,这个功能可以在js中进行模拟。

    三种方法:

    第一种:扩展Object方法

     1 Object.prototype.ext=function(parObject){//Object.prototype.ext在原型链上定义的ext所有的对象都可以访问到
     2     //循环遍历父类对象所有属性
     3     for(var i in parObject){
     4         //为子类对象添加这个遍历到的属性
     5         //它的值是父类对象这个属性的属性值
     6         this[i] = parObject[i];
     7     }
     8 }
     9 function Person(p_name,p_age){
    10     this.name=p_name;
    11     this.age=p_age;
    12     this.speak=function(){
    13         alert(this.name+this.age);
    14     }
    15 }
    16 function Student(p_no){
    17     this.no=p_no;
    18     this.say=function(){
    19         alert(this.no+this.name_this.age);
    20     }
    21 }
    22 var stu = new Student(101);
    23 stu.ext(new Person('xiaoqiang',20));
    24 stu.speak();
    25 stu.say();

    第二种:使用call和apply方法

     1 function Person(p_name,p_age){
     2     this.name=p_name;
     3     this.age=p_age;
     4     this.speak=function(){
     5         alert(this.name+this.age);
     6     }
     7 }
     8 function Student(p_no,p_name,p_age){
     9     this.no=p_no;
    10     this.say=function(){
    11         alert(this.name+this.age+this.no);
    12     }
    13     Person.call(this,p_name,p_age);//this是上下文,后面的参数是传递给person的参数,参数的先后顺序要一一对应,如果是用apply则后面的参数要用数组
    14 }
    15 var stu = new Student(8,'zhagsan',18);
    16 stu.speak();
    17 stu.say();

    第三种:原型继承

     1 function Person(p_name,p_age){
     2     this.name=p_name;
     3     this.age=p_age;
     4     this.speak=function(){
     5         alert(this.name+this.age);
     6     }
     7 }
     8 function Student(p_no){
     9     this.no=p_no;
    10     this.say=function(){
    11         alert(this.name+this.age+this.no);
    12     }
    13 }
    14 Student.prototype = new Person('wangwu',21);
    15 var stu = new Student(10);
    16 stu.speak();
    17 stu.say();
  • 相关阅读:
    [CF1469D] Ceil Divisions
    [CF632D] Longest Subsequence
    [CF1215E] Marbles
    [CF689D] Friends and Subsequences
    [CF707D] Persistent Bookcase
    [CF10D] LCIS
    [CF713C] Sonya and Problem Wihtout a Legend
    [CF1114E] Arithmetic Progression
    [CF1404B] Tree Tag
    [CF710E] Generate a String
  • 原文地址:https://www.cnblogs.com/sunnie-cc/p/6269194.html
Copyright © 2011-2022 走看看