[英]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: 相反,我写了一个非常简单的示例,这是我的工作:
get
to it which is an object itself. get
的属性添加到它本身就是一个对象。 elem
in elem.get.text()
the time when execution reaches inside text()
function: 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
当它达到b
在ab()
不使用全局变量。
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.