zoukankan      html  css  js  c++  java
  • js对象之间的继承

    js的对象之间的继承抛弃了原型与构造器的概念,而转为字面量对象之间进行属性拷贝的方式进行继承。 

    首先我们来写一个封装好的继承函数:

    function extend(parent){
        var child={};
        for(var i in parent){
            child[i]=parent[i];
        }
        child.uber=parent;
        return child;
    }

     函数有一个形参parent,函数内部新建一个空的子对象,这个子对象就像一个白的画板,逐渐的将父对象上的内容临摹上去。for循环当中是将父对象中的属性和方法逐个复制给子对象。再将子对象的uber指向父对象,这样调用子对象的uber属性就可以调用父对象的属性和方法了,这相当与java中的super,为什么js当中不用super呢,因为super在js中是保留字,所以采用德语与“super”同义的“uber”来替代。

    下面来看看这个函数的实际应用,首先创建一个父对象:

    var Shape={
        color:"blue",
        name:"shape",
        getName:function(){
            return this.name;
        }
    }

    接着我们来实现继承,并扩展和重写子对象的一些方法:

    var circle=extend(Shape);
    circle.name="circle";
    circle.getName=function(){
        return "parentName:"+this.uber.getName()+" childName:"+this.name;
    }
    circle.getS=function(){
        return this.radius*this.radius*3.14;
    }
    circle.init=function(radius){
        this.radius=radius;
    }


    首先使用extend函数实现继承

    子对象添加了新的name属性和新的getName方法,还有扩展的getS方法和init初始化方法

    getName中this.uber.getName()调用父对象的getName()方法,得到父对象的name属性,this.name得到自身的name属性。

    接下来执行方法:

    circle.init(5);
    console.log(circle.name+","+circle.uber.name);
    console.log(circle.getName()+","+circle.uber.getName());
    console.log(circle.getS());
    
    /*
    结果:
    circle,shape
    parentName:shape childName:circle,shape
    78.5
    */
    爱写代码的孩子运气不会太差。 github:http://github.com/lavyun 新浪微博:http://weibo.com/u/5921186675 个人网站: http://lavyun.cn
  • 相关阅读:
    HUSTOJ:Transit Tree Path
    HUSTOJ:5500 && 洛谷:P1412:经营与开发
    hdu:2036.改革春风吹满地
    hdu:2030.汉字统计
    Leetcode:338. Bit位计数
    【学习笔记】圆方树(CF487E Tourists)
    BZOJ3238 [Ahoi2013]差异
    CF 187D BRT Contract
    CF 36E Two Paths
    CF 49E Common ancestor
  • 原文地址:https://www.cnblogs.com/smartXiang/p/5890952.html
Copyright © 2011-2022 走看看