javascript - 如何从该对象内部的函数访问数组对象的属性
问题描述
function CreateInfoBoxCard(){
var newBox = {
"location":currentLoc, // dynamically set location at the time of Creation
"addHandler":"mouseover",
"infoboxOption": {
title: 'title',
description: "description",
actions: [{
label:'Remove This',
eventHandler: function () {
removeBox(currentLoc)
// WANT TO USE THIS "CurrentLoc AT THAT TIME" AS ID TO REMOVE THIS OBJECT LATER
//but it will always take "current location" as param, which I don't want
}
}] }
}
setState((Collection)=>[...Collection, new])
}
这是一个将被推入数组内部的对象,它将成为 bing 地图中的一个信息框。eventHandler 键在必应地图上的每个信息卡上创建一个按钮。现在单击该按钮,我想根据“位置”键(对象的第一个键)删除此特定对象。在这里,currentLoc 变量是动态的。因此,如果我单击删除按钮,它将删除当前位置的信息框,而不是创建信息框时的位置。因此,我想访问该对象的“位置”键的值并将其传递给 removeBox("//pass here//") 函数,而不是在此处传递 currentLoc 变量。那么,我怎样才能从这个功能中访问“位置”键呢?
解决方案
包含 的对象location
应该可以被操作中定义的 eventHandler 访问。因此,要使用它,只需使用obj.location
. 这将允许 eventHandler 始终获取最新值,即使它在创建后被更改。
使用上述方法,上述代码将更改为:
function CreateInfoBoxCard(){
var card = {
location: "currentLoc",
addHandler: "mouseover",
infoboxOption: {
title: "title",
description: "description",
actions: [{
label: "Remove This",
eventHandler: function () {
removeBox(card.location);
}
}]
}
}
return card;
}
function removeBox(location) {
//Some logic to remove a box
console.log(location);
}
//Calling `CreateInfoBoxCard` function to get a new card
var card1 = CreateInfoBoxCard();
card1.infoboxOption.actions[0].eventHandler();
//Updating the location of the card and calling it's eventHandler again
card1.location = "someNewLocation";
card1.infoboxOption.actions[0].eventHandler();
注意:对象名称必须更改(例如更改为卡片),因为new
它是一个受限关键字。