【问题标题】:How to access JavaScript object properties from a prototype method of the object [duplicate]如何从对象的原型方法访问 JavaScript 对象属性 [重复]
【发布时间】:2015-04-10 02:07:38
【问题描述】:

我不知道如何命名这个问题,但这是我的困境。我有一个封装和继承方法的 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>

所以如果你运行这段代码sn-p,点击add链接添加锚标签,你会注意到当你点击X按钮锚点时,它会触发removeListItem函数,this.readOnly是不可访问的,因为this是指到锚标签。

【问题讨论】:

    标签: javascript oop prototype


    【解决方案1】:

    您可以使用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();

    【讨论】:

    • 谢谢,我马上试试。
    • @HectorCervantes 不客气!
    • 谢谢你,Vohuman,这就像一个魅力!
    猜你喜欢
    • 2012-07-12
    • 1970-01-01
    • 2014-11-26
    • 2019-09-25
    • 2013-12-07
    • 2019-02-04
    • 2021-11-06
    • 1970-01-01
    • 2012-09-29
    相关资源
    最近更新 更多