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 );