OOP javascript对象继承(父/子)

时间:2011-09-21 02:45:12

标签: javascript

你好我正在使用Javascript OOP,我无法让它工作。我想通过子句从另一个对象(父)调用函数。这是我的“班级”代码:

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”和“render”,如下所示:

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

1 个答案:

答案 0 :(得分:1)

替换:

Character.inheritsFrom(Unit);

with:

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

请参阅此jsFiddle Example