• javascript类式继承


    javascript中是没有类这个概念的,但是javascript有它自己的原型机制,我们可以通过原型机制(prototype,constructor)来伪一个类出来,俗称“伪类”。

    新函数对象被创建时,会被赋予一个prototype属性,它的值是一个包括constructor属性,且属性值为该新函数的对象,用代码来解释就是:

    Cat.prototype.constructor = Cat

    介绍javascript原型机制的文章博客园有很多,可以自己找来看看哦。

    构建伪类的第一步是定义一个构造器:

    function Animal(kind) {
        this.kind = kind || "哺乳类"
    }

    第二步就是扩充它的原型:

    Animal.prototype.getKind = function() {
      return this.kind
    }

    接下来就可以实例化啦,是不是很简单啊,想实例化多少个都可以哦

    var aaa = new Animal("两栖类")
    var bbb = new Animal("飞禽类")
    console.log(aaa.getKind()) //两栖类
    console.log(bbb.getKind()) //飞禽类

    好了,介绍完怎么构建伪类之后该进入正题了,那我们如何来实现“继承者们”呢?

    Step One:

    我们的目的是继承,继承当然是要给Animal生个儿子(没儿子怎么继承)那父亲是个类,儿子也必须是个类啦,所以还是老步骤。

    function Cat() {
      Animal.call(this, "哺乳类")
    }

    Cat是子类的构造函数,那么问题来了,Animal.call(this)是什么东西?其实它在这里的作用就是调用父类的构造函数。

    Step Two:

    Cat.prototype = new Animal()

    这句话是类继承的关键,把Animal的实例赋值给Cat的prototype,这样Cat的原型就拥有了Animal的原型的方法和属性,但是又不会影响到Animal。

    Step Three:

    Cat.prototype.constructor = Cat

    由于Cat.prototype之前被卖给了Animal,所以Cat.prototype的构造函数指向了Animal,这句代码的作用就是把Cat再弄回来。

    上面都是类式继承的基本步骤,下面我们来个实例试试看:

    function Animal(kind) {
      this.kind = kind || "哺乳类"
    }
    Animal.prototype.getKind = function() {
      return this.kind
    }
    
    function Cat() {
      Animal.call(this, "哺乳类")
    }
    Cat.prototype = new Animal()
    Cat.prototype.constructor = Cat
    Cat.prototype.miao = function() {
      return "我是子类独有的方法哦,喵~"
    }
    var aaa = new Animal("两栖类")
    var bbb = new Animal("飞禽类")
    console.log(aaa.getKind()) //两栖类
    console.log(bbb.getKind()) //飞禽类
    var cat_aaa = new Cat()
    console.log(cat_aaa.getKind()) //哺乳类
    console.log(Cat.prototype.constructor) //指向Cat,如果之前不改回来,指向的会是Animal
    //console.log(aaa.miao()) //undefined is not a function 父类是用不了miao的哦
    console.log(cat_aaa.miao())

    结果是不是都是期望的值呢?

    有兴趣的同学可以试试console.log(cat_aaa), 看看会出现什么。

    如果需要继承的地方很多,那一直这么重复去写类似的继承方式会很麻烦,所以我们来定义一个inherits方法,会使继承的实现更简洁:

    Function.prototype.inherits = function(func) {
        this.prototype = new func()
        this.prototype.constructor = this
    }

    代码很容易看懂吧,接下来看看应用:

    function Animal(kind) {
      this.kind = kind || "哺乳类"
    }
    Animal.prototype.getKind = function() {
      return this.kind
    }
    function Cat(name) {
      Animal.call(this, "哺乳类")
    }
    Cat.inherits(Animal);
    Cat.prototype.miao = function() {
      return "我是子类独有的方法哦,喵~"
    }
    var cat_bbb = new Cat()
    console.log(cat_bbb.miao())

    ok,完工了,继续改bug去~

  • 相关阅读:
    flask 中的request
    悲观锁、乐观锁、行级锁、表级锁
    python标准库--functools.partial
    Django Model._meta API
    python中的urlencode与urldecode
    Django模版语言inclusion_tag的用法。
    Django的URL别名
    Django之模板语言
    django-request对象
    Java 基础
  • 原文地址:https://www.cnblogs.com/junhua/p/4308310.html
Copyright © 2020-2023  润新知