适当的Javascript继承 [英] Proper Javascript inheritance

查看:93
本文介绍了适当的Javascript继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在javascript中继承构造函数。在以下示例中,我希望 Moveable 分配 x y 参数 this.x this.y 的对应关系,正如我在<$ c $中定义的那样C>精灵。此外,在没有创建祖先的情况下定义原型的最佳方式(但仍然简短且可读)是什么?最好将它分配给类本身,而不是像现在这样在外部范围内分配:

I am wondering whether it is possible to inherit constructor in javascript. In the following example, I'd like the Moveable to assign x and y arguments to this.x and this.y respectivelly, as I defined in Sprite. Also, what would be the best way (but still short and readable) to define the prototype without creating the instation of ancestor? It would be best to assign it in the class itself, not in the outside scope as I it is now:

function Sprite(x, y) {
    this.x = x ? x : 0;
    this.y = y ? y : 0;     
    this.getPos = function() {
        return {
            x: this.x,
            y: this.y
        };
    };
}

function Moveable(x, y) {

}
Moveable.prototype = new Sprite();


推荐答案

调用超类构造函数的标准方法是使用< a href =https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call> Function.call

The standard way to call a superclass constructor is using Function.call:

function Moveable(x, y) {
  Sprite.call(this, x, y);
}

至于原型,你可以做这样的事情来链接原型而不用创建超类的实例:

As for the prototype, you can do something like this to chain the prototype without creating an instance of the superclass:

function makePrototype(superclass) {
  function f() { }
  f.prototype = superclass.prototype;
  return new f();
}

Moveable.prototype = makePrototype(Sprite);

这使用虚拟构造函数创建一个与共享相同原型的对象Sprite ,由于这是所有JavaScript关心的, Moveable 的实例被视为 instanceof Sprite

This uses a dummy constructor to create an object that shares the same prototype as Sprite, and since that's all JavaScript cares about, instances of Moveable are considered instanceof Sprite.

这不像你要求的那样简短易读,但唯一的另一种选择是完全跳过原型并直接在构造函数中分配成员。

This isn't "short and readable" as you asked for, but the only other choice is to entirely skip prototypes and assign members directly within the constructor.

编辑:正如@Raynos指出的那样,您还需要设置构造函数属性(这是由JavaScript默认完成的,但是一旦你重置 Moveable.prototype 就会丢失:

As @Raynos points out, you also want to set the constructor property (which is done by default by JavaScript but is lost as soon as you reset Moveable.prototype):

Moveable.prototype.constructor = Moveable;

这篇关于适当的Javascript继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆