【问题标题】:How do you call a method inherited from another class?如何调用从另一个类继承的方法?
【发布时间】:2015-12-15 20:25:14
【问题描述】:

此代码不能在最后一行运行。我不知道为什么。

var Vehicle = function() {
	var age = 21;			//private variable
	this.setAge = function(age2) {age = age2;};
	this.getAge = function() {return age;};
};

var Plane = function() {};
Plane.prototype = Object.create(Vehicle.prototype);

var plane = new Plane();
console.log( plane instanceof Vehicle );
//console.log( plane.getAge() );	//TypeError: plane.getAge is not a function

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您的新飞机的构造函数有一个空函数,并且从未在其上调用过 Vehicle 构造函数。您应该从平面构造函数调用 Vehicle 构造函数,方法是:

    var Plane = function() {};
    

    到:

    var Plane = function ( ) {
        Vehicle.call( this );
    };
    

    【讨论】:

      【解决方案2】:

      可以通过以下方式扩展对象

      var Vehicle = function() {
          var age = 21;           //private variable
          this.setAge = function(age2) {age = age2;};
          this.getAge = function() {return age;};
      };
      
      var Plane = function(){
          Vehicle.apply(this, arguments);
      };
      Plane.prototype = Object.create(Vehicle.prototype);
      
      var plane = new Plane();
      console.log( plane instanceof Vehicle , plane.getAge());
      

      jsFiddle

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-30
        • 2015-09-19
        • 1970-01-01
        • 2021-02-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多