实现javascript继承

implementing javascript inheritance

本文关键字:继承 javascript 实现      更新时间:2023-09-26

我正在尝试理解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.

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

首先,有两个小问题:

  • 在JavaScript中大小写很重要。Object.create需要小写,你的函数名不匹配(subClass vs SubClass)。通常,构造函数的函数名是大写的。
  • 使用属性this.name(这是继承的)而不是变量name(这是未定义的)-参见Javascript:我需要把这个。Var为对象中的每个变量?

如何正确实现继承

将方法(不需要特权,在构造函数作用域中没有局部变量)移动到原型对象上。并且让SubClass.prototypeBaseClass.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()不显示来自baseClass的name属性

调用构造函数时没有任何参数。idcompanyname属性的值为undefined。此外,您的SubClass甚至没有name的参数,并且它不向BaseClass构造函数调用传递任何内容。