2013-11-26 64 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