2011-09-21 171 views
1

你好,我正在使用Javascript OOP,我無法讓它工作。我想通過孩子從另一個對象(父母)調用函數。這是我的「類」代碼:OOP JavaScript對象繼承(父/子)

function Unit(_x, _y, _speed) { 
    this.x = _x; 
    this.y = _y; 
    this.dx = _speed; 
    this.dy = _speed; 
    this.gravity = 0; 
} 
Unit.prototype.apply_gravity = function() { 
    this.gravity+=global_gravity; 
    this.y+=this.gravity; 
} 
Unit.prototype.render = function() { 
    context.drawImage(images[0], canvas_screen.x+this.x, canvas_screen.y+this.y); 
} 

function Character() { 
} 

Character.inheritsFrom(Unit); 

我希望能夠調用的函數:「apply_gravity」,並從角色對象這樣的「渲染」:

var character = new Character(100,100,5); 
character.render(); 

回答

1

替換:

Character.inheritsFrom(Unit); 

有:

Character.prototype = new Unit(0,0,0); // or whatever defaults if you want them 

硒e這jsFiddle Example

+2

我想'inheritsFrom'是一些第三方庫(也許使用不正確,如果它是[Type.inheritsFrom](http://msdn.microsoft.com/en-us/library/bb397427.aspx)) ,儘管我沒有進一步調查的衝動。 – 2011-09-21 02:52:23