【问题标题】:Clarification on Prototype and Object.create pattern关于 Prototype 和 Object.create 模式的说明
【发布时间】:2016-06-28 13:38:40
【问题描述】:

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

我有一个动物课。它有sayName 方法。

Cat1 使用 Prototype 模式从 Animal 继承。

Cat2 使用 Object.create 模式从 Animal 继承。

在 cat1 的情况下,是否可以像 cat1.sayName("Cat1") 那样调用 sayName 而不是 cat1.prototype.sayName("Cat1");

以cat2为例,是否可以定义Cat2自己的属性和函数,然后像Animal一样继承

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

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

这样我就可以有一个干净的结构。我不想用like

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

请澄清。

【问题讨论】:

  • 你必须如此奇怪地调用cat1.prototype.sayName,因为这不是原型继承
  • Object.create 不支持多重继承。但是您可以通过concatenation 从多个原型中继承
  • cat1.prototype 被视为普通财产吧?那么如何在 Cat1 中继承 Animal

标签: javascript javascript-objects javascript-inheritance


【解决方案1】:

换行

obj.prototype = animalObj;

Object.setPrototypeOf(obj, animalObj);

你可以打电话

cat1.sayName("Cat1");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    • 2017-06-18
    相关资源
    最近更新 更多