Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/444.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何访问父对象“;这";从它在JS中的功能?_Javascript - Fatal编程技术网

Javascript 如何访问父对象“;这";从它在JS中的功能?

Javascript 如何访问父对象“;这";从它在JS中的功能?,javascript,Javascript,如何访问第this.property1=options.p1行中的this对象实例从第行this.id=id以便设置id属性?使用 (function( $ ) { var TagHolder = function(element,options){ this.property1 = options.p1; this.id = 0; this.init = function(){ $('a').on('click

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

使用

(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 );
在TagHolder函数中,然后执行以下操作

self = this;

在init函数中,将对该函数的引用存储在父函数的变量中,然后使用self-In引用父函数上下文,例如self.id

self.id = id;

标记持有者
中创建
this
的引用,即
var this=this
,然后设置
\u this.id=id
或者您可以使用ES6箭头函数,这样您就可以在单击函数时将
函数(e)
替换为
()=>
。jQuery将元素作为上下文绑定到所有处理程序。所以
$(这个)
引用了附加的元素。@Speir arrow函数是一个坏选项。它胜过了的
$(此)
功能jQuery@Rajesh这取决于你的喜好,在这种情况下,我认为你是对的。
(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 );