【问题标题】:Manage JS inheritance failure管理 JS 继承失败
【发布时间】:2016-04-26 14:57:03
【问题描述】:

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

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() 获取关于“soundsystem extras”的私有变量

非常感谢。

【问题讨论】:

  • 在第二个示例中,您从未将任何内容分配给 myCar
  • 你从不使用Extras
  • 你不需要return,当计划使用函数作为构造函数时
  • 您使用的不是构造函数,而是工厂函数。 myCar 不从 Car 或 Extras 函数继承任何东西。
  • @SergiuParaschiv 你知道,我知道,但是对于学习的人来说,首先以简单的方式学习它会很棒,然后才进入原型继承。语法很重要 IMO :)

标签: javascript oop inheritance


【解决方案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>');

对于 ES2015,您可以使用 classes

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>');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 2017-07-06
    • 2016-09-18
    • 1970-01-01
    相关资源
    最近更新 更多