Вопрос

Suppose we have an abstract class Animal:

function Animal(){};
Animal.prototype.communicate = function(metadata){
   //ABSTRACT
};

And then we have a Duck class:

function Duck(){};
Duck.prototype = new Animal();
Duck.prototype.communicate = function(metadata){
   console.log("Cuack!");
}; 

So, I'm writting a Greasemonkey script and I really need to save some animals in localstorage to retrieve them the next time the page will be loaded (this way allows me to re-create the same instances I had before reaload page).

So, I really need the classname of every Animal created. I read another similar questions and the way they get the classname is:

var aDuck = new Duck();
console.log("ClassName: " + aDuck.constructor.name);

But when I do this I get "ClassName: Animal" on console. P/d: I can't change programming style with prototype, it is a requirement... :(

Any suggestions? Thanks for your time!

Это было полезно?

Решение 3

To ask the object ID it's the same thing that ask object class. The solution is double dispatching. See here: http://en.wikipedia.org/wiki/Double_dispatch

Другие советы

Duck.prototype = new Animal();

This code is wrong; the correct way to do prototypal inheritance is a little more complicated.

If you can't change it directly, you can still fix it in Greasemonkey:

Duck.prototype.constructor = Duck;

You'll need to do that for each class.

The (not perfect, but) correct way would be, first calling the Animal constructor in Duck's context

function Duck() {
    Animal.call(this);
}

And then what you did:

Duck.prototype = new Animal();

And then explicitly making the Duck's instances' constructor point to Duck:

Duck.prototype.constructor = Duck; 
// so that all new Duck() 's constructor point to Duck

PS: Not to offend, the more complicated link given by @Slack uses Object.create, new JavaScript method, to do it. There's no fallback for JavaScript < 1.8. I feel OO JS at MDN explains a better (but not perfect) attempt for older JS

Object.create has come into picture for this very inheritance which you want to achieve (Child class extending the Parent):

function inherits(Parent, Child) {
    function F() {}
    F.prototype = Parent;
    Child.prototype = new F();
}

Object.create perfect-izes the above method, famously known as Crockford's Prototypal Inheritance Way and implements it natively.
But is available only in modern versions of Browsers (which I know is the major share now)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top