Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/428.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将对象强制转换为自定义类_Javascript_Jquery_Class_Casting - Fatal编程技术网

Javascript 将对象强制转换为自定义类

Javascript 将对象强制转换为自定义类,javascript,jquery,class,casting,Javascript,Jquery,Class,Casting,我正在开发一个HTML5应用程序 在Javascript中,我定义了一个自定义类和一个哈希表实现: function Card(newId, newName, newDescription) { this.id = newId; this.name = newName; this.description = newDescription; } function HashTable() { var hashTableItems = {}; this.Se

我正在开发一个HTML5应用程序

在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时,我不知道如何将返回的对象强制转换为Card类

var cardObject = $.viacognitaspace.cards.GetItem(cardNumber);
此处,
cardObject
未定义

如果我这样做:

$('#cardName').text(cardObject.name);
我犯了一个错误


如何修复此问题?

尝试将代码修改为以下内容:

$.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);
您还需要创建一个
哈希表函数的实例

示例:


我们需要查看代码的其余部分。您是否在卡号位置添加了一些内容--这对我来说似乎是个问题。
cardObject
未定义意味着它不在哈希表中,但这与强制转换无关。如果你只“设置”卡对象,你将只“获取”卡对象(或未定义),我已经更新了我的问题。现在,您可以看到我如何向HastTable添加Card对象。