简体   繁体   English

如何访问嵌套对象中的父对象

[英]How to get access to parent object in a nested object

I'm looking for a way to get access to parent object when I use nested objects, I have a complex situation so I can't offer a real example here. 我正在寻找一种使用嵌套对象时访问父对象的方法,我处在一个复杂的情况下,因此无法在此处提供真实的示例。

I wrote a very simple example instead, here's what I do: 相反,我写了一个非常简单的示例,这是我的工作:

  1. I get a JavaScript object by queryselector(). 我通过queryselector()获得了一个JavaScript对象。
  2. Then I add my own property named get to it which is an object itself. 然后,我将自己的名为get的属性添加到它本身就是一个对象。
  3. I want to get access to parent JavaScript object when the nested object is called, I mean elem in elem.get.text() the time when execution reaches inside text() function: 我想在调用嵌套对象时获得对父JavaScript对象的访问权,这意味着elem.get.text()elem执行到达text()函数内部的时间:

 //***** Initialization: var get = { text: function(){ //Here I want to know what was the elem return elem.textContent; }, foo: function(){}, bar:{ text: function(){ //And also here which is one level deeper return elem.textContent; } } }; var elem = document.querySelector("#elem"); elem.get = Object.create(get); //***** function getText(e){ var elem = e.target; alert(elem.get.text()); } 
 <input type="button" id="elem" onclick="getText(event)" value="Get Text"/> 

I emphasis again that it's merely a simple example so don't criticize that I could get the text of input through a much easier way. 我再次强调,这只是一个简单的示例,所以不要批评我可以通过一种更简单的方法来获取输入文本。

In fact I want to know how to get access to a when it reaches to b in ab() without using a global variable. 其实我想知道如何获得访问a当它达到bab()不使用全局变量。

You could save the reference to elem when creating new get instance using Object.create . 使用Object.create创建新的get实例时,可以保存对elem的引用。

 //***** Initialization: var get = { text: function() { //Here I want to know what was the elem return this.elem.value; // use this.elem to access element }, foo: function() {}, bar: function() {} }; var elem = document.querySelector("#elem"); elem.get = Object.create(get, { elem: { // keep current element ref value: elem } }); //***** function getText(e) { var elem = e.target; console.log(elem.get.text()); } 
 <input type="button" id="elem" onclick="getText(event)" value="Get Text" /> 

Also I've update text to use value instead of textContent for demo purposes because input has no text content. 另外,出于演示目的,我已经更新了text以使用value而不是textContent ,因为input没有文本内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM