简体   繁体   English

从另一个对象(JavaScript / jQuery)访问对象属性

[英]Accessing object properties from within another object (JavaScript / jQuery)

I am trying to access properties of a config object from within another object: 我正在尝试从另一个对象中访问配置对象的属性:

var myConfigObj = {
  $myCachedSelector: $('#mySelector')
}

var myObj = {
  $selector: myConfigObj.$myCachedSelector,
  url: 'http://www.someurl.com/somepath'
}

$.each([ myObj, mySecondObj, myThirdObj ], function() {
  this.$selector.load(this.url, function(){
  //do something
}); 

When trying to use $selector in the each function then, it returns "undefined". 然后,当尝试在每个函数中使用$ selector时,它将返回“ undefined”。 Both objects are in the same scope, and I don't know what the problem is. 这两个对象都在同一范围内,我不知道问题出在哪里。

This code worked well enough for me, with a few minor tweaks: 这段代码对我来说已经足够好了,但做了一些小的调整:

  • This is probably the problem: Firefox is complaining about the semicolon, should be: 这可能是问题所在:Firefox抱怨分号,应该是:

     var myConfigObj = { $myCachedSelector: $('#mySelector') } 
  • Should be in $(document).ready , of course. 当然应该在$(document).ready中。
  • Missing some }); 缺少一些}); at the end (probably a copy/paste thing) 最后(可能是复制/粘贴的东西)
  1. Install Firebug in Firefox; 在Firefox中安装Firebug
  2. In the "Scripts" pane, set a breakpoint on the line that causes the error; 在“脚本”窗格中,在导致错误的行上设置一个断点;
  3. When stopped at the breakpoint, examine this in the right-hand "Watch" pane; 当在断点处停了下来,审视this在右边的“观察”窗格中;
  4. If the this object you're stopped on has a $selector property which has a load method then it's not the cause of your problem, so continue round the loop. 如果您在this对象上停下来的对象具有$selector属性,该属性具有load方法,那么这不是问题的根源,因此请继续循环。
  5. When the this object doesn't have a $selector property, or has one that doesn't have a load method, you've found your culprit. this对象具有$selector属性,或者具有不具有load方法的属性时,您就找到了罪魁祸首。 Now work out why you are sending it into that loop, or where you are failing to initialise it. 现在,找出为什么要将其发送到该循环中,或者在何处未能对其进行初始化。

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

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