gpt4 book ai didi

javascript - 在 javascript 中传递引用

转载 作者:行者123 更新时间:2023-11-29 14:58:55 26 4
gpt4 key购买 nike

这是我的第一篇 SO 帖子。我永远感谢这个社区拥有和分享的信息。谢谢。

我来自 Flash,我什至不确定该问什么才是正确的。我所能做的就是列出我的代码示例,然后解释我要做什么。我没有完全理解我在这里试图说明的术语,所以我觉得最好省略它们。

下面的代码不完整,因为它只包含我认为与我的问题相关的部分。请参阅我的代码中的注释以查看我的问题。

编辑:完整源文件在这里:[链接已删除] console.log 输出有问题的问题。

    <script type="text/javascript"> 
var a_chests = [];
var chestID = 0;

//I'm creating a plugin to be able to make multiple instances
(function ($) {
$.fn.chestPlugin = function (option) {
//This function creates a master sprite object which many of my sprites will use
//I've simplified the features to get to the heart of my question
var DHTMLSprite = function (params) {
var ident = params.ident,
var that = {
getID: function(){
return ident;
}
};
return that;
};

//ChestSprite inherits DHTMLSprites properties and then adds a few of its own
var chestSprite = function(params) {
var ident = params.ident,
that = DHTMLSprite(params);
that.reveal=function(){
console.log(ident);
};

return that;
};

//Here I create multiple instances of the chests
var treasure = function ( $drawTarget,chests) {
for (i=0;i<chests;i++){
var cs = chestSprite({
ident: "chest"+chestID
})
console.log(cs.reveal())
//This logs "chest0", "chest1", "chest2" as the for loop executes
//This behavior is correct and/or expected!

a_chests[chestID]={id:i,ob:cs};
//I add a reference to the new chestSprite for later

chestID++;
//increment the chestID;
}
console.log(a_chests[1].ob.reveal());
//This always logs "chest2" (the last chest that is created), even though
//the logs in the for loop were correct. It seems it is referencing the
//DHTML object (since the DHTMLSprite function returns that;) and since
//there is no reference to which chest I need, it passes the last one.

//Is there any way I can pass a reference to DHTMLSprite in order to retain
//the reference to the three individual chests that are created?

//Is there another solution altogether? Thanks!!!
};

//The rest of the code.
return this.each(function () {
var $drawTarget = $(this);
treasure($drawTarget,3);
});
};
})(jQuery);


</script>

最佳答案

您忘记将“that”声明为局部变量,因此它在每次迭代时都会被覆盖。

    var chestSprite = function(params) {
var that;
var animInterval;
...

关于javascript - 在 javascript 中传递引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13105465/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com