管理JS继承失败

时间:2016-04-26 14:57:04

标签: javascript oop inheritance

我是面向对象编程的新手,请记住。我已经理解了这里显示的第一部分是如何工作的(确实如此):

function Car() {

    var  __registration;

    var setReg = function(val) {
         __registration= val;
    }

    var getReg= function() {
        return  __registration;
    }


    return {
        setReg: setReg ,
        getReg: getReg

    }

}

var myCar = new Car();
myCar.setReg("LSKM5215");
alert(myCar.getReg() );   //ALERTS LSKM5215

但是当尝试以这种面向对象编程的方式管理继承时,它只会一次又一次地失败:

function Extras(){

    var  __sound;

    var setSound= function(val) {
         __sound= val;
    }

    var getSound= function() {
        return  __sound;
    }


    return {
        setSound: setSound,
        getSound: getSound

    }

}

Extras.prototype = new Car();

myCar.setSound("SUPERB SOUNDSYSTEM 2.2");    //TypeError: myCar.setSound is not a function

我怎样才能在这种情况下创建继承?要使Car()获得关于" soundystem extras" 的私有变量?

非常感激。

1 个答案:

答案 0 :(得分:1)

当计划使用函数作为构造函数时,您不需要return

在派生类中,您应该使用所需的参数调用基础构造函数。

在派生类中基于基本原型分配proptotype。

这样的事情:



function Car() {

  var __registration;

  this.setReg = function(val) {
    __registration = val;
  }

  this.getReg = function() {
    return __registration;
  }

}

function Extras() {
  Car.call(this);
  var __sound;

  this.setSound = function(val) {
    __sound = val;
  }

  this.getSound = function() {
    return __sound;
  }

}

Extras.prototype = Object.create(Car.prototype);

myExtras = new Extras();
myExtras.setReg("LSKM5215");
myExtras.setSound("SUPERB SOUNDSYSTEM 2.2");

document.write("<div>Extras: reg - ", myExtras.getReg(), '</div>');
document.write("<div>Extras: sound - ", myExtras.getSound(), '</div>');
&#13;
&#13;
&#13;

对于ES2015,您可以使用classes

&#13;
&#13;
class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }

  get area() {
    return this.calcArea();
  }

  calcArea() {
    return this.height * this.width;
  }
}

class Car {

  constructor() {
    this.__registration = undefined;
  }

  set Reg(val) {
    this.__registration = val;
  }

  get Reg() {
    return this.__registration;
  }

}

class Extras extends Car {

  constructor() {
    super();
    this.__sound = undefined;
  }

  set Sound(val) {
    this.__sound = val;
  }

  get Sound() {
    return this.__sound;
  }

}

myExtras = new Extras();
myExtras.Reg = ("LSKM5215");
myExtras.Sound = ("SUPERB SOUNDSYSTEM 2.2");

document.write("<div>Extras: reg - ", myExtras.Reg, '</div>');
document.write("<div>Extras: sound - ", myExtras.Sound, '</div>');
&#13;
&#13;
&#13;