0

<html>
    <head>
        <meta charset="UTF-8">
        <title>Animal</title>
        <script type="text/javascript" >

            var Animal = function () {
                return {
                    sayName: function (name) {
                        alert("My name is " + name);
                    }
                }
            }
            // Animal object
            var animalObj = new Animal();
            // Cat1 inherits from animalObj using prototype pattern.
            var Cat1 = function () {
                var obj = {
                    run: function () {
                        alert("I am running...");
                    },
                };
                obj.prototype = animalObj;
                return obj;

            }

            // Cat1 inherits from animalObj using Object.create pattern.
            var Cat2 = function () {
                var obj = Object.create(animalObj);
                obj.run = function () {
                    alert("I am running...");
                };
                return obj;

            }
            var cat1 = new Cat1();
            cat1.prototype.sayName("Cat1");
            cat1.run();

            var cat2 = new Cat2();
            cat2.sayName("Cat2");
            cat2.run();

        </script>
    </head>
    <body>
    </body>
</html>

I have a Animal class. It has sayName method.

Cat1 inherits from Animal using Prototype pattern.

Cat2 inherits from Animal using Object.create pattern.

In the case of cat1, is it possible to invoke sayName like cat1.sayName("Cat1") instead of cat1.prototype.sayName("Cat1");?

In the case of cat2, is it possible to define the Cat2's own properties and functions and then inherit the Animal like

var Cat2 = function () {
       var obj = {
           run: function () {
               alert("I am running...");
           },
       };

       // Here I want obj inherits Animal. How can I do that?
       return obj;
}

So that I can have a clean structure. I doesn't want to use like

obj.run = function () {
    alert("I am running...");
};

Please clarify.

Kiren S
  • 3,037
  • 7
  • 41
  • 69
  • You have to invoke `cat1.prototype.sayName` so oddly, because this isn't prototypal inheritance –  Jun 28 '16 at 13:45
  • `Object.create` doesn't support multiple inheritance. But you can inherit from several prototypes by [concatenation](http://stackoverflow.com/questions/2800964/benefits-of-prototypal-inheritance-over-classical) –  Jun 28 '16 at 13:51
  • cat1.prototype is treated as a normal property right? So how can I inherit Animal in Cat1 – Kiren S Jun 30 '16 at 14:28

1 Answers1

-1

Replace line

obj.prototype = animalObj;

with

Object.setPrototypeOf(obj, animalObj);

And you can call

cat1.sayName("Cat1");
Anton Tupy
  • 951
  • 5
  • 16