簡體   English   中英

你如何調用從另一個類繼承的方法?

[英]How do you call a method inherited from another class?

此代碼無法在最后一行運行。 我不知道為什么。

 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 

您的新平面的構造函數具有空函數,並且從未在其上調用Vehicle構造函數。 您應該通過更改以下內容從平面構造函數中調用Vehicle構造函數:

var Plane = function() {};

至:

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

擴展對象可以通過以下方式完成

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM