Clarification on Prototype and Object.create pattern

52 Views Asked by At

<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.

1

There are 1 best solutions below

0
On

Replace line

obj.prototype = animalObj;

with

Object.setPrototypeOf(obj, animalObj);

And you can call

cat1.sayName("Cat1");