zoukankan      html  css  js  c++  java
  • javascript中uber实现子类访问父类成员

    function Animal(){}
    Animal.prototype={
        name:"animal",
        toString:function(){
            console.log(this.name);
        }
    };
    Animal.prototype.constructor=Animal;
    function Dog(){}
    //用于打破对象的引用传递,防止修改子类属性对父类产生影响
    var F=function(){}
    F.prototype=Animal.prototype
    Dog.prototype=new F();
    Dog.prototype.constructor=Dog;
    Dog.prototype.name="dog";
    var d=new Dog();
    d.toString(); //打印子类name dog
    var a=new Animal();
    a.toString();//打印父类name animal

    上面代码通过实例化子类和父类,分别调用toString()实现了继承的关系。

    这个时候有这样的需求;不实例化父类,直接通过子类完完整整的调用父类的方法或属性。

    实现代码如下

    function Animal(){}
    Animal.prototype={
        name:"animal",
        toString:function(){
            console.log(this.name);
        }
    };
    Animal.prototype.constructor=Animal;
    function Dog(){}
    //用于打破对象的引用传递,防止修改子类属性对父类产生影响
    var F=function(){}
    F.prototype=Animal.prototype
    Dog.prototype=new F();
    Dog.prototype.constructor=Dog;
    Dog.prototype.name="dog";
    Dog.uber=Animal.prototype;
    var d=new Dog();
    d.toString(); //打印子类name dog
    //var a=new Animal();
    //a.toString();//打印父类name animal
    
    /**
     * Dog.prototype.constructor===d.constructor
     */
    Dog.prototype.constructor.uber.toString();//打印animal(方式1)
    d.constructor.uber.toString(); //打印animal(方式2)

    通过面简单的三行红色代码就实现了子类访问父类成员的需求。

    本来想模仿java的使用super访问父类,后来想想super是javascript的关键字。

  • 相关阅读:
    js -- use strict
    css布局—— 固定+自适应
    web前端安全问题(转载)
    清除float浮动
    源码核心动画01-CALayer-基本使用(了解)
    源码0308-画板
    源码0306-手势解锁
    源码0301-图片水印-裁剪-截屏-截取-擦除
    源码0309-雪花(定时器)-图形上下文状态栈-矩阵操作
    源码0308-模仿UIImageView
  • 原文地址:https://www.cnblogs.com/guoyansi19900907/p/12093829.html
Copyright © 2011-2022 走看看