如何从对象的原型方法访问JavaScript对象属性

How to access JavaScript object properties from a prototype method of the object

本文关键字:对象 访问 JavaScript 属性 方法 原型      更新时间:2023-09-26

我不知道如何为这个问题命名,但这是我的难题。我有一个JS对象,我已经封装并继承了方法。其中一个方法插入一个锚标记,其中onclick事件指向同一对象的一个固有方法。在第二种方法中,我遇到了麻烦,因为当用户触发锚标记的点击事件时,"this"关键字现在就是锚元素。因此,这阻止了我通过"this"关键字访问对象中的属性。这是我的简化代码,所以你可以看到我在说什么。

<!DOCTYPE html>
<html>
<head>
  <title>Working out an issue</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
  <script>
    function ListContainerViewer(name, readOnly) {
      this.name = name;
      this.readOnly = readOnly;
    }
    ListContainerViewer.prototype = {
      constructor: ListContainerViewer,
      addListItem: function(itemId, content) {
        var removeBtn = $('<a href="#"><span class="glyphicon glyphicon-remove pull-right" aria-hidden="true"></span> </a>')
          .clone()
          .click(this.removeListItem); // Here, "this" points to ListContainerViewer
        removeBtn.appendTo($("#selectedItemList"));
      },
      removeListItem: function() {
        if (this.readOnly == true) { // how do I point to ListContainerViewer.readOnly if this points to <a>?
          event.preventDefault();
          return;
        } else {
          this.remove(); // this should point to <a> that has the click event
        }
      }
    }
    var listContainer;
    $(document).ready(function() {
      listContainer = new ListContainerViewer('test', true);
      $('#button').click(function() {
        listContainer.addListItem('12345', 'test content');
      });
    });
  </script>
</head>
<body>
  <h1>Testing OO JS</h1>
  <a id='button' href='#'>Click to add</a>
  <div id="selectedItemList" style="{width: 800px; height: 400px; background-color: #dddddd}"></div>
</body>
</html>

因此,如果您运行此代码片段,单击添加链接以添加锚点标记,您会注意到,当您单击X按钮锚点时,它会触发removeListItem函数,this.readOnly不可访问,因为它指的是锚点标记。

您可以使用Function.prototype.bind或jQuery $.proxy方法来设置函数的this值:

.click(this.removeListItem.bind(this));

现在,在您的函数中,this指的是实例,而不是单击的元素。为了获得点击的元素,您可以使用event对象的currentTarget属性:

removeListItem: function(event) {
    var element = event.currentTarget;
    // ...    
}

请注意,您使用的是DOM HTMLElement.remove方法,而不是jQuery对象的remove方法。较旧的浏览器不支持该方法。建议使用jQuery构造函数封装元素并使用它的remove方法:$(element).remove();