2013-02-26 48 views
0

我在JavaScript中构建一个纸牌游戏以增加我的web编程排序,并且我遇到了JavaScript Prototype继承的问题。我的设计有一个基卡类,它包含了任何卡所需的所有功能和数据。设计本身是相对灵活的,所以只需通过更改存储的数据大约25%的卡片就可以使用基类。我需要做的是创建新的类,它继承了Card的所有内容(包括数据),但是覆盖可用函数的一小部分而不触及基类功能。JavaScript - 原型继承而不覆盖基类

我一直在尝试使用原型继承来完成这个任务,但是这改变了基类,它不仅使用Card类将任何卡片拧紧,而且还从基类继承其他每个函数。

我需要的是一种设计模式,它允许我只为从卡继承的类重写函数。这是可能的JavaScript?

编辑...

对不起,这里是一个例子,probally应首先增加了这一点。

从基卡类开始。现在

function Card(){ 
    this.cardID = 0; 
    this.name = ''; 
    this.imageID = 0; 
    this.imageURL = ''; 
    this.imageAlt = ''; 
    etc.... 
} 

Card.prototype.init = function(inID 
    , inName 
    , inImageID 
    , inImageURL 
    , inImageAlt 
    , inImageHorizontal 
    etc... 
){ 
    this.cardID = inID; 
    this.name = inName; 
    this.imageID = inImageID; 
    this.imageURL = inImageURL; 
    this.imageAlt = inImageAlt; 
} 

Card.prototype.whenPlayed = function(){ 
    return false; 
} 

我的子类:

ChildCard.prototype = new Card(); 
ChildCard.constructor = ChildCard; 
function ChildCard(){}; 

ChildCard.prototype.whenPlayed = function(){ 
    alert("You Win!"); 
    return true; 
} 

目前的情况是,如果我要创建一个Card对象,并调用其whenPlayed我会得到ChildCard行为不卡。

我真的在这里面临的问题是卡类有3种方法,我不想在每个子类中定义每个方法。

+0

是的,这是可能的。 – Bergi 2013-02-26 20:20:07

+1

听起来像你想简单的JavaScript继承http://ejohn.org/blog/simple-javascript-inheritance/ – QuentinUK 2013-02-26 20:20:55

+0

@QuentinUK:没有。这不会帮助理解问题。 – Bergi 2013-02-26 20:23:45

回答

7

相当简单和直接的方式:

function Parent(arg) { 
    this.someProperty = arg; 
    // initialize all instance properties in the constructor 
} 


// The prototype should only contain methods and primitive values. 
Parent.prototype.someMethod = function() { 
    // ... 
}; 

Parent.prototype.someOtherMethod = function() { 
    // ... 
}; 


function Child(arg1, arg2) { 
    // call parent constructor -- like super() in other languages 
    Parent.call(this, arg1); 
    // initialize all instance properties in the constructor 
} 

// Hook up Base.prototype into the prototype chain 
Child.prototype = Object.create(Parent.prototype); 
Child.prototype.constructor = Child; // not necessary but can be useful 

Child.prototype.someMethod = function() { 
    // override method and call parent method 
    Base.prototype.someMethod.call(this); 
    // ... 
}; 

它依赖于Object.create[MDN]。它创建一个从传入的对象继承的新对象。因此,您可以在Child.prototypeParent.prototype之间获得一个间接级别,即对Child.prototype的更改不会影响`Parent.prototype