popup_data={ 俱乐部:{ type:“俱乐部”, 类型(_img):{ header:'CLUB header', img:' https://source.unsplash.com/random/800x600 ', sub_header:'俱乐部子标题', content:'文本', 热点位置:[5,-1.5,2.5] }, 热点阵列(hotspots_array):[ {id:()=>this.club.type+'-'+'type_img', 位置:()=>this.club.type_img.hotspot_position, }, ] },
-
如果有多个对象,可以创建一个实用程序来绑定函数。 – 基思 评论 2022年4月5日10:42
3个答案
popup_data={ 俱乐部:{ type:“俱乐部”, 类型(_img):{ header:'CLUB header', img:' https://source.unsplash.com/random/800x600 ', sub_header:'俱乐部子标题', content:'文本', 热点位置:[5,-1.5,2.5] }, 热点阵列(hotspots_array):[ {id:()=>popup_data.club.type+“-”+“type_img”, 位置:()=>popup_data.club.type_img.hotspot_position, }, ] },
是什么 这 ? 在JavaScript中
这 关键字是指 对象 .
哪个 对象取决于如何
这 正在被调用(使用或调用)。
这个
这 关键字根据其使用方式引用不同的对象:
在对象方法中,
这 指的是 对象 . 独自一人,
这 指全局 对象 . 在函数中,
这 指的是 全局对象 . 在函数中,在严格模式下,
这 是 未定义 . 在某一事件中,
这 指的是 要素 收到事件的。 方法如
调用() ,
应用() 、和
绑定() 可以引用
这 到 任何对象 .
popup_data={ 俱乐部:{ 类型:“俱乐部”, 类型(_img):{ header:'CLUB header', img:' https://source.unsplash.com/random/800x600 ', sub_header:'俱乐部子标题', content:'文本', 热点位置:[5,-1.5,2.5] }, 热点阵列(hotspots_array):[ {id:()=>popup_data.club.type+“-”+“type_img”, 位置:()=>popup_data.club.type_img.hotspot_position, }, ] },
函数id(){ return this.club.type+“-”+“type_img”; } 功能位置(){ 返回this.club.type_img.hotspot_position; } const弹出数据={ 俱乐部:{ type:“俱乐部”, 类型(_img):{ header:'CLUB header', img:' https://source.unsplash.com/random/800x600 ', sub_header:'俱乐部子标题', 内容:“文本”, 热点位置:[5,-1.5,2.5] }, 热点阵列(hotspots_array):[ { name:'测试', id,位置 }, { name:'测试2', id,位置 } ] } }; const popup_data_2={ 俱乐部:{ type:'这是俱乐部2', 类型(_img):{ 热点位置:[5,-1.5,2.5] }, 热点阵列(hotspots_array):[ { id,位置 } ] } }; 函数bindFunctions(r,a){ Object.entries(a).map(([k,v])=>{ const tp=v型; if(tp===“函数”){ a[k]=v.bind(r); }else if(tp===“对象”){ bindFunctions(r,v); } }); } bindFunctions(弹出数据,弹出数据); bindFunctions(popup_data_2,popup_data_2); console.log(popup_data.club.hotspots_array[0].id()); console.log(popup_data.club.hotspots_array[0].position()); 控制台.log(popup_data_2.club.hotspots_array[0].id());
函数makeObject(数据){ const root=数据; for(data.club.hotspots_array的常数){ //现在让我们添加函数 h.id=()=>root.club.type+“-”+“type_img”; h.位置=()=>根.club.type_img.hotspot_position; h.array=data.club.hotpots_array; } 返回根; } const o1=生成对象({ 俱乐部:{ type:“俱乐部”, 类型(_img):{ header:'CLUB header', img:' https://source.unsplash.com/random/800x600 ', sub_header:'俱乐部子标题', content:'文本', 热点位置:[5,-1.5,2.5] }, 热点阵列(hotspots_array):[ { name:'测试', }, { name:'测试2', } ] } }); console.log(o1.club.hotspots_array[0].id()); 控制台.log(o1.club.hotspots_array[0].position()); console.log('array:'+o1.club.hotspots_array[0].array.length);