javascript - 实现 JavaScript 继承

标签 javascript inheritance

我正在尝试理解 javascript 中的继承

function baseClass(name) {
   this.name = name;
   this.getName = function() {
       return this.name;
   }
}



function subClass(id, company){
       baseClass.call(this);
       this.id = id;
       this.company = company;
       this.toString = function() {
           return name + "\n" + this.id + "\n" + this.company; 
       }  
   }



subClass.prototype = Object.create(baseClass);
   var s = new subClass();
   s.toString();  //here the name property from the baseClass is not displayed.

如何正确实现继承(经典/原型(prototype))

最佳答案

首先,有两个小问题:

How do correctly implement inheritance

将方法(不需要特权,构造函数范围内没有局部变量)移动到原型(prototype)对象上。并且让 SubClass.prototype 继承自 BaseClass.prototype,而不是继承自 BaseClass 函数。

function BaseClass(name) {
   this.name = name;
}
BaseClass.prototype.getName = function() {
   return this.name;
};

function SubClass(id, company){
    BaseClass.call(this);
    this.id = id;
    this.company = company;
}
SubClass.prototype = Object.create(BaseClass.prototype);
SubClass.prototype.toString = function() {
   return this.name + "\n" + this.id + "\n" + this.company; 
};

new SubClass().toString() does not display the name property from the baseClass

您正在调用不带任何参数的构造函数。 idcompanyname 属性将具有 undefined 值。此外,您的 SubClass 甚至没有 name 参数,并且它不会将任何内容传递给 BaseClass 构造函数调用。

关于javascript - 实现 JavaScript 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16021577/

相关文章:

javascript - 如何在React Native 'Share'函数中设置动态url

javascript - 如何在 jstree 负载上打开选定(选中)的节点?

单例模式的Swift继承?

inheritance - 继承catalog.xml中magento中的类别布局更新

c++ - 从值类继承还是复合呢?

c# - 什么是阅读 ISomething : ISomethingElse 的正确方法

javascript - JSSOR - 幻灯片转换期间奇怪的字幕行为

javascript - 在图像之间淡入淡出

javascript - JQuery 事件选择器

c++ - 从类继承,在不同的命名空间中定义