简体   繁体   English

访问构造函数创建的对象中的属性

[英]Accessing properties in objects created by constructors

I have a for loop like so: 我有一个for循环,像这样:

for (var i = 0; i < 10; i++) {
  obj[i] = new MapArea(some passed variables);
}

Now this constructor has a few predefined properties as well as some defined at initialization. 现在,此构造函数具有一些预定义的属性以及一些在初始化时定义的属性。 As the for loop would suggest, each obj is held inside it's own index within the array obj[]. 正如for循环所建议的那样,每个obj都保存在数组obj []中自己的索引内。 My issue is that after I have iterated through initialization, I cannot reference the properties of individual objects with a 我的问题是,遍历初始化之后,我无法使用

this.propertyName;

or 要么

$(this).propertyName;

The plugin I am building operates off mouse events (clicks and hovers) meaning I need to be able to check the obj attached to the event for specific properties on it's current state but have no way of programmatically knowing what index it is in the array to reference it, or at least doing so easily and concisely. 我正在构建的插件会根据鼠标事件(单击和悬停)进行操作,这意味着我需要能够检查与事件相关的obj的当前状态的特定属性,但无法以编程方式知道数组中的索引是什么引用它,或者至少这样做简单而简洁。

Has anyone encountered this problem and found a solution or am I pretty much forced into using the array and index as a reference? 有没有人遇到过这个问题并找到了解决方案,还是我被迫使用数组和索引作为参考? Any help would be awesome. 任何帮助都是极好的。

here is one of my methods for example: 这是我的一种方法,例如:

$.fn.clickLight = function(options) {
  var defaults = $.extend( {
    color : "#43464B",
    opacity : "0.3"
  }, options);
  ctx.globalAlpha = defaults.opacity;

  $(area_ref).click(function(event) {
    $(this).handleMouse(event).each(function() {
      if (!$(this).clicked) { // I try and access here
        console.log(obj.this.clicked);
        $(this).highlight(defaults.color);
        $(this).clicked = true;
      } else {
        console.log(this.clicked);
        $(this).clearlight();
        $(this).clicked = false;
      }
    } );
  } );

  $(area_ref).hover(function() {
    $(this).handleMouse().each(function() {
      $(this).highlight(defaults.color);
    } );
  },function() {
    if (!$(this).clicked){ // I try and access here
      $(this).handleMouse().each(function() {
        $(this).clearLight();
       } );
    }
  } );
  return $(this);
};

You can use the data function of jQuery to bind an object to a DOM element. 您可以使用jQuery的数据功能将对象绑定到DOM元素。 So you can do something like the following to store your objects: 因此,您可以执行以下操作来存储对象:

$('#clickableElement1').data('mapArea', new MapArea(some passed variables));

And something like the following to retrieve an object given an event: 以及类似以下内容的对象,以获取给定事件的对象:

var mapArea = $(event.currentTarget).data('mapArea');

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

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