简体   繁体   English

如何使JavaScript函数继承正确运行

[英]How to make JavaScript function inheritance work right

I've got a problem. 我有一个问题。 I'm working on a fairly large JavaScript project, and I'm learning how to use OOP. 我正在从事一个相当大的JavaScript项目,并且正在学习如何使用OOP。 It's kind of weird in JS, as I'm sure you know. 我确定您知道,在JS中有点奇怪。

So here's what I'm trying to do: I've got a base 'class', that I call AbstractAnimal . 因此,这就是我想要做的事情:我有一个基本的“类”,我称之为AbstractAnimal I've got another class called Animals . 我还有另一门课叫做Animals Inside of the Animals class I have three groups, called Man , Monkey , and Elephant . 在“ Animals类中,我分为三类,分别是“ Man ,“ Monkey ”和“ Elephant I want each of those groups to inherit AbstractAnimal , but to be their own functions, not connected to AbstractAnimal . 我希望每个组都继承AbstractAnimal ,但要成为自己的函数,而不要与AbstractAnimal连接。

I was originally doing that like this: 我本来就是这样做的:

Animals.prototype.Man = AbstractAnimal;
Animals.prototype.Monkey = AbstractAnimal; //etc...

However, that doesn't do what I need it to do, sadly. 但是,可悲的是,这并不能满足我的需要。 Here's why: 原因如下:

AbstractAnimal.prototype.clicked = function() { console.log("clicked") };
//If I change Man...
animals.Man.clicked = function() { console.log("HA!"); };
//Monkey is effected too...
animals.Monkey.clicked();
//Console: "HA!"

In the example above, when Monkey is clicked I would want the console to say "clicked". 在上面的示例中,当单击Monkey时,我希望控制台说“ clicked”。 When Man is clicked, it should say "HA!". 单击“人”时,应显示“ HA!”。

So I found something that I thought would do it over here: javascript class inherit from Function class 所以我发现我认为可以在这里完成的工作: javascript类从Function类继承

And it almost worked, but not quite. 它几乎起作用了,但效果不尽如人意。 Here's a reduced test case: http://jsfiddle.net/9KRJk/2/ 这是一个简化的测试用例: http : //jsfiddle.net/9KRJk/2/

Could'ja help me out? 可以帮我吗? Thanks! 谢谢!

PS No, actually, the whole animal thing is metaphorical, I'm not actually programming a zoo. PS:不,实际上,整个动物事物都是隐喻的,我实际上不是在编写动物园。 :) :)

Don't know if I quite understand your problem, but maybe you're complicating things too much or maybe you're missing some concepts, but your prototype chain can be represented like this: 不知道我是否完全理解您的问题,但是也许您使事情变得过于复杂,或者可能缺少了一些概念,但是原型链可以这样表示:

// Extends helper
Function.prototype.extends = function( parent ) {
  this.prototype = Object.create( parent.prototype );
};

function Animal() {}
Animal.prototype = {
  clicked: function() {
    console.log('animal');
  }
};

function Man() {}
Man.extends( Animal );
Man.prototype.clicked = function() {
  console.log('man');
};

function Monkey() {}
Monkey.extends( Animal );
Monkey.prototype.clicked = function() {
  console.log('monkey');
};

var animal = new Animal();
animal.clicked(); //=> 'animal'

var man = new Man();
man.clicked(); //=> 'man'

var monkey = new Monkey();
monkey.clicked(); //=> 'monkey'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM