【问题标题】:Inheritence with Javascript? how to get the 'super' or 'base'用Javascript继承?如何获得“超级”或“基地”
【发布时间】:2012-04-09 23:06:11
【问题描述】:

我有以下代码:

function Person(){
    this.age = 30;
}

function Stats(){
    this.age = 20
}

Stats.prototype = new Person();

var fred = new Person();


console.log(fred.age)

我想做的是理解 Javascript 中的继承,我怎样才能做到上述并在统计和人员中获取年龄属性?

【问题讨论】:

  • 我不认为我真的理解你的问题。

标签: javascript inheritance superclass


【解决方案1】:

您还可以使用 Object.getPrototypeOf(obj),如 this answer 中所述。但我不得不修改你的代码来做到这一点。我认为您想实例化 Stats 对象,而不是其父对象。这是你的意图吗?

function Person(){
    this.age = 30;
}

function Stats(){
    this.age = 20
}

Stats.prototype = new Person();

// Note that this is not your code example
var fred = new Stats();

console.log(fred.age)


console.log(Object.getPrototypeOf(fred).age);

【讨论】:

    【解决方案2】:

    Javascript 支持经典继承和原型继承。 大多数其他语言仅支持经典继承。

    var person1 = {"fname" : "Amit", "lname":"Agar"};
    var SubPerson = function(){};
    SubPerson.prototype = person1;
    var person2 = new SubPerson();
    

    参考javascript the good parts

    【讨论】:

      【解决方案3】:

      JavaScript 足够好,可以让你实现你想要的。您的用例要求在创建新类型时调用所有构造函数。考虑以下几点:

      function defineClass(ctor, baseType) {
      
         function classFunction() {
             if (baseType) {
               baseType.apply(this);
             };
             ctor.apply(this);
         }
      
        if (baseType) {
           ctor.prototype = Object.create(baseType.prototype);
           ctor.prototype.constructor = ctor;
        }
           classFunction.prototype = Object.create(ctor.prototype);
      
           return classFunction;
       }
      

      现在你可以定义你的两种类型了:

      function fruit() { console.log("fruit ctor"); }
      
      var apple = defineClass(function apple() { console.log("apple ctor"); }, fruit);
      

      创建一个新苹果:

      new apple;
      

      控制台:

      = 水果 ctor

      = 苹果演员

      【讨论】:

        【解决方案4】:

        查看 MDN 中的“面向对象 JavaScript 简介”:https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript

        【讨论】:

          【解决方案5】:

          你不能。 JavaScript 不做经典继承,而是原型继承。看看crockford's article on this(以及其他许多人。)

          由于personstats 的原型,任何属于person 原型的部分都将通过在实例化对象中设置该属性来覆盖。

          但很酷的部分是,如果您更改原型,所有以该对象为原型的对象都会收到更改。

          有一些项目试图将经典继承填充到 JavaScript 中,但与其对抗它,你应该学会接受它。

          【讨论】:

          • 谢谢你,虽然这不应该让我很难理解,但谢谢你的 2 美分,或者更确切地说是我的 2 美元,因为它很有用。你能告诉我原型的定义吗?也会阅读道格拉斯·克罗克福德的文章。
          【解决方案6】:

          其实因为javascript没有经典的对象模型,所以无法获取父对象...

          PS 在你的例子中“父类”是Person,所以当你创建新的人时,父类将是对象

          【讨论】:

            猜你喜欢
            • 2021-01-29
            • 2017-05-02
            • 2014-09-02
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-08-17
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多