2013-11-26 63 views
2

我一直在玩javascript多年,但我現在想要認真對待。學習,並進入對象。用不同的方法創建2個其他對象的javascript基礎對象

我想創建一個基礎對象,並用它來創建另外兩個略有不同的對象。

我想這會工作:

function movingObject(x, y, z){ 
    this.x = x; 
    this.y = y; 
    this.z = z; 
} 

var positiveMover = new movingObject(x, y, z); 
positiveMover.prototype.move = function(a, b){ 
    yadda yadda 
} 

var negativeMover = new movingObject(x, y, z); 
negativeMover.prototype.move = function(b, a){ 
    adday adday 
} 

var pic = postiveMover(1, 2, 3); 
pic.move(20, 10); 

我得到一個未定義的錯誤上舉.....很肯定我有錯誤的想法。任何意見,將不勝感激 - 信息的鏈接,或者合適的關鍵詞,以谷歌

+0

在JavaScript中,'x.prototype'不是「x的原型」。 – georg

+0

我正在將移動功能添加到negativeMover對象 – user3036025

回答

0

我覺得它更像是兩個類,即要構建:

function movingObject(x, y, z){ 
    this.x = x;  this.y = y;  this.z = z; 
} 

// positive mover : child class of movingObject  
function positiveMover (x, y, z) { 
    // use parent class's constructor. 
    movingObject.apply(this,arguments); 
}; 

// inherit parent's class. 
positiveMover.prototype = Object.create(movingObject.prototype); 

positiveMover.prototype.move = function(a, b){ yadda yadda } 

但是,如果你尋求以每個例如選擇的方法,你可以這樣做:

function movingObject(x, y, z, movingMethod){ 
    this.x = x;  this.y = y;  this.z = z; 
    this.move = movingMethod; 
} 

或者只設置一個移動物體的移動屬性,從而覆蓋默認的原型:

function movingObject(x, y, z){ 
    this.x = x;  this.y = y;  this.z = z; 
} 
movingObject.prototype.move= function(a,b) { /*some default code*/} 

var oneMover = new movingObject(0,0,0); 
oneMover.move = function(a,b) { /* some specific code */ }; 
+0

感謝GameAlchemist!對等實例選擇實際上是我所追求的,但我很欣賞其他兩個選項的教訓,以及 – user3036025

+0

不客氣! – GameAlchemist