首页 > 解决方案 > 如何从 JS 中的函数访问父对象“this”?

问题描述

(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 属性?this.property1 = options.p1;this.id = id;

标签: javascript

解决方案


采用

self = this;

在您的 TagHolder 函数中,然后执行

self.id = id;

在你的初始化函数中


推荐阅读