2012-02-11 96 views
0

我正在开发HTML 5应用程序。将对象投射到自定义类

在Javascript中我已经定义了一个自定义类和散列表实施方案:

function Card(newId, newName, newDescription) 
{ 
    this.id = newId; 
    this.name = newName; 
    this.description = newDescription; 
} 

function HashTable() 
{ 
    var hashTableItems = {}; 

    this.SetItem = function(key, value) 
    { 
     hashTableItems[key] = value; 
    } 

    this.GetItem = function(key) 
    { 
     return hashTableItems[key]; 
    } 
} 

我使用哈希表来添加卡的对象。我使用此代码添加卡:

... 
var card = new Card(id, name, description); 

$.viacognitaspace.cards.SetItem(id, card); 
... 

我的问题是,当我打电话HashTable.GetItem,我不知道怎么投对象返回卡类。

var cardObject = $.viacognitaspace.cards.GetItem(cardNumber); 

这里,cardObject是未定义的。

如果我这样做:

$('#cardName').text(cardObject.name); 

我得到一个错误。

我该如何解决这个问题?

+2

我们需要看到代码的其余部分。你是否在卡号位置添加了一些东西 - 这对我来说似乎是个问题。 – Hogan 2012-02-11 16:39:12

+0

'cardObject'未定义表示它不在散列表中,但与cast无关。如果你只“设置”卡片对象,你只会“获取”卡片对象(或未定义) – ori 2012-02-11 16:40:33

+0

我已经更新了我的问题。现在,您可以看到如何将卡对象添加到HastTable。 – VansFannel 2012-02-11 16:42:36

回答

0

尝试修改您的代码如下:

$.viacognitaspace = {} /* define namespace if not already defined... */ 

var card = new Card(id, name, description); 

/* the "new" keyword creats an instance of your HashTable function 
    which allows you to reference and modify it later on... */ 
$.viacognitaspace.cards = new HashTable(); 

$.viacognitaspace.cards.SetItem(id, card); 

您还需要创建HashTable function的一个实例。

例子:

http://jsfiddle.net/3BWpM/