zoukankan      html  css  js  c++  java
  • javascript实现继承方法

    javascript继承概念:js是基于对象的,他没有类的概念,所以实现继承,需要使用js的原型prototype机制或者用applay和call方法实现

    1、原型链继承

    为了让子类继承父类的属性(也包括方法),首先需要定义一个构造函数。然后,将父类的新实例赋值给构造函数的原型。

    function parent(){

      this.name="garuda";

    }

    function child(){

      this.sex="man"

    }

    child.prototype=new parent();//核心:子类继承父类,通过原型形成链条

    var test=new child();

    console.log(test.name);

    console.log(test.sex);

    备注:在js中,被继承的函数称为超类型(父类、基类),继承的函数称为子类型(子类、派生类)。

        使用原型继承存在两个问题:一是面量重写原型会中断关系,使用引用类型的原型,二是子类型还无法给超类型传递参数

    2、借用构造函数继承

    function parent(){

      this.name="garuda";

    }

    function child(){

      parent.call(this);//核心:借父类型构造函数增强子类型(传参)

    }

    var test =new parent();

    console.log(test.name);

    3、组合继承(原型链和构造函数组合)

    function parent(){

      this.name="garuda";

    }

    function borther(){

      return this.name;

    }

    function child(){

      parent.call(this)

    }

    child.prototype=new parent();

    var test=new parent();

    console.log(test.borther())

  • 相关阅读:
    Mvc form提交
    FlexiGrid 使用 全选、自动绑定
    Mysql Insert Or Update语法例子
    orderby与groupby同时使用
    SQLSTATE[HY000] [2002] No such file or directory in
    swoole安装
    关于商城分类查询表结构与数据查询
    查询数据库每张表的信息
    php 正则验证
    PHP代码优化
  • 原文地址:https://www.cnblogs.com/wangpengfei8313/p/8302537.html
Copyright © 2011-2022 走看看