【问题标题】:How can I access parent object "this" from its function in JS? [duplicate]如何从 JS 中的函数访问父对象“this”? [复制]
【发布时间】:2019-06-09 03:00:23
【问题描述】:
(function( $ ) {

    var TagHolder = function(element,options){

        this.property1 = options.p1;
        this.id = 0;

        this.init = function(){
           $('a').on('click',function(e){
              e.preventDefault();

              var id = $(this).attr('id');
              this.id = id;
           });
        }
    }

    $.fn.TagHolderProperty = function(options) {
        return new TagHolder(this, options);
    }
})( window.jQuery );

如何从this.id = id; 行访问this.property1 = options.p1; 行中的this 对象实例,以便设置id 属性?

【问题讨论】:

  • TagHolder 中创建this 的引用,即var _this=this,然后设置_this.id = id
  • 或者你可以使用 ES6 箭头函数,所以你可以在点击函数上用() => 替换function(e)
  • jQuery 将元素作为上下文绑定到所有处理程序。所以$(this) 指的是附加元素。
  • @Speir 箭头函数是一个不好的选择。它击败了 jQuery 的$(this) 功能
  • @Rajesh 这取决于你的喜好,在这种情况下我认为你是对的。

标签: javascript


【解决方案1】:

使用

self = this;

在你的 TagHolder 函数中然后做

self.id = id;

在你的初始化函数中

【讨论】:

    【解决方案2】:

    在父函数的变量中存储对 this 的引用,然后使用 self in 来引用父函数上下文,例如自我.id

    (function( $ ) {
    
        var TagHolder = function(element,options){
           var self = this;
    
    
            this.property1 = options.p1;
            this.id = 0;
    
            this.init = function(){
               $('a').on('click',function(e){
                  e.preventDefault();
    
                  var id = $(this).attr('id');
                  self.id = id;
               });
            }
        }
    
        $.fn.TagHolderProperty = function(options) {
            return new TagHolder(this, options);
        }
    })( window.jQuery );
    

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 2011-07-08
      • 2011-04-05
      • 2018-06-24
      • 1970-01-01
      • 1970-01-01
      • 2018-03-26
      • 1970-01-01
      • 2023-03-13
      相关资源
      最近更新 更多