简体   繁体   中英

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. It's kind of weird in JS, as I'm sure you know.

So here's what I'm trying to do: I've got a base 'class', that I call AbstractAnimal . I've got another class called Animals . Inside of the Animals class I have three groups, called Man , Monkey , and Elephant . I want each of those groups to inherit AbstractAnimal , but to be their own functions, not connected to 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". When Man is clicked, it should say "HA!".

So I found something that I thought would do it over here: javascript class inherit from Function class

And it almost worked, but not quite. Here's a reduced test case: 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. :)

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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