如何用Javascript(jQuery)调用“基类”函数?

时间:2016-10-03 10:06:04

标签: javascript jquery oop

我想在Javascript中创建两个函数类:Animal和Zebra。客户端脚本用于实例化Zebra,然后Zebra应该能够从Animal中查看和调用函数:

斑马:动物

因此,我尝试了以下内容,我使用jQuery $.extend()将Animal作为Zebra的基类:

Animal = function() {
    function hi_animal() {
        console.log('But I am also an animal');
    }

    return {
        hi_animal: hi_animal
    }
}

Zebra = function() {
    $.extend(this, Animal);

    function hi_zebra() {
        console.log('I am a zebra!');

        hi_animal();
    }

    return {
        hi_zebra: hi_zebra
    }
}

$(document).ready(function() {
   var my_zebra = new Zebra();
   my_zebra.hi_zebra();
});

浏览器日志应显示以下两行:

  

我是斑马郎   但我也是一个动物

但是,我只看到:

  

我是斑马!   未捕获的ReferenceError:未定义hi_animal

这是fiddle

我错过了什么?

2 个答案:

答案 0 :(得分:3)

JS中的类继承语法不正确。 $.extend旨在转置对象属性。它对函数/类的任何影响纯属巧合。

您应该定义基类,然后对派生实例进行原型设计。试试这个:



function Animal() {
  // put constructor logic here...
}
Animal.prototype.hi_animal = function() {
  console.log('But I am also an animal');
}

Zebra.prototype = new Animal();
Zebra.prototype.constructor = Zebra; // otherwise constructor will be Animal()
function Zebra() {
  // put constructor logic here...
}
Zebra.prototype.hi_zebra = function() {
  console.log('I am a zebra!');
  this.hi_animal();
}

$(document).ready(function() {
  var my_zebra = new Zebra();
  my_zebra.hi_zebra();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

@Rory McCrossan的回答是完全正确的。 但我喜欢Javascript的一件事是原型系统是如何工作的。以下是Rory的略微修改版本,但没有使用原型链,这可能具有性能优势,因为它使原型链更加平坦。在C#/ Delphi等世界中,它就像你可以操纵VMT一样。

&#13;
&#13;
function Animal() {
  // put constructor logic here...
}
Animal.prototype.hi_animal = function() {
  console.log('But I am also an animal');
}

function Zebra() {
  // put constructor logic here...
}
Zebra.prototype.hi_zebra = function() {
  console.log('I am a zebra!');
  this.hi_animal();
}
Zebra.prototype.hi_animal = Animal.prototype.hi_animal;

$(document).ready(function() {
  var my_zebra = new Zebra();
  my_zebra.hi_zebra();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;