2017-06-29 3 views
1

metalSingerオブジェクトは、オブジェクトSingerのプロトタイプ関数のみを継承します。シンガー(this.genre)と関数(this.rock)の変数をどのように継承できますか?JavaScriptで変数を継承する方法は?

答えて

0

クラスパターンは継承で使用できます。あなたはこれを達成することができます

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance

function Singer(g) { 
    this.genre = g; 
    this.rock = function() { 
    console.log("ROCK"); 
} 
} 

Singer.prototype.sing = function() { 
    console.log(this.genre); 
} 

function MetalSinger(g) { 
    Singer.call(this, g); 
} 

var ms = new MetalSinger("foo"); 
console.log(ms.rock()); 
0

一つの方法は、このような子コンストラクタ内で親コンストラクタ関数を呼び出すことである:

function Singer(g) { 
 
    this.genre = g; 
 
    this.rock = function() { 
 
    console.log("ROCK"); 
 
    } 
 
} 
 

 
Singer.prototype.sing = function() { 
 
    console.log(this.genre); 
 
} 
 

 
function metalSinger() { 
 
    Singer.call(this, 'metal'); 
 
} 
 

 
metalSinger.prototype = Object.create(Singer.prototype); 
 

 
var james = new metalSinger(); 
 
james.sing();

この方法で構築する前に、子オブジェクトでは、オブジェクトを初期化するために親コンストラクタが最初に呼び出されます。

0

シンガー(this.genre)と関数(this.rock)の変数をどのように継承できますか?そうすることによって

Singer.call(this, genre); 

metalSingerthisオブジェクトにその(歌手の)プロパティを追加しmetalSingerのコンテキストであなたの最初の呼び出しSinger:このような基本的

。また、Object.create()で新しいオブジェクトを作成し、すべての関数をPrototypeに入れる方が良いでしょう。

function Singer(g) { 
 
    this.genre = g; 
 
} 
 
Singer.prototype.sing = function() { 
 
    console.log(this.genre); 
 
} 
 
Singer.prototype.rock = function() { 
 
    console.log("ROCK"); 
 
} 
 

 
function metalSinger(g) { 
 
    Singer.call(this, g); 
 
} 
 

 
metalSinger.prototype = Object.create(Singer.prototype); 
 

 
var james = new metalSinger("metal"); 
 
james.sing(); // "metal" 
 
james.rock(); // "ROCK"

関連する問題