Jquery 插件动态添加输入字段,self 和 this 是什么
Jquery Plugin Adding Input fields dynamically, what is self vs this
因此,一旦我的插件被调用,我就会添加一个输入字段,即
function myPlugin ( element, options ) {
this.element = element;
this.settings = $.extend({}, $.fn.myPlugin.defaults, options );
this.init();
this.setUpSearchField()
}
// Avoid Plugin.prototype conflicts
$.extend(myPlugin.prototype, {
init: function () {
if ($.isFunction(this.settings.onInit())) {
this.settings.onInit();
}
},
setUpSearchField: function () {
//Adding Input Field to Div
var self = this;
this.$searchField = $("<input/>", {
id: 'control'
})
.appendTo(this.element)
.focus(function () {
self.$searchField.val("");
})
}
});
我在设置 .focus 时遇到的问题是有效的代码
self.$searchField.val("");
但如果我最初尝试做
this.$searchField.val("");
我收到一条错误消息,指出`this.$searchField 未定义。如果有人能解释一下,我不明白这种情况的区别?
$.extend
块中的 this
将引用参数中的对象,而 focus
事件处理程序中的 this
将引用引发的元素事件处理程序。
为了消除这些之间的歧义,在父对象中 this
被存储到 self
变量中,以便可以在事件处理程序中引用它。
举例说明:
$.extend(myPlugin.prototype, {
// this = the object
var self = this;
$('#foo').focus(function () {
// this = the #foo element
// self = the object
});
});
因此,一旦我的插件被调用,我就会添加一个输入字段,即
function myPlugin ( element, options ) {
this.element = element;
this.settings = $.extend({}, $.fn.myPlugin.defaults, options );
this.init();
this.setUpSearchField()
}
// Avoid Plugin.prototype conflicts
$.extend(myPlugin.prototype, {
init: function () {
if ($.isFunction(this.settings.onInit())) {
this.settings.onInit();
}
},
setUpSearchField: function () {
//Adding Input Field to Div
var self = this;
this.$searchField = $("<input/>", {
id: 'control'
})
.appendTo(this.element)
.focus(function () {
self.$searchField.val("");
})
}
});
我在设置 .focus 时遇到的问题是有效的代码
self.$searchField.val("");
但如果我最初尝试做
this.$searchField.val("");
我收到一条错误消息,指出`this.$searchField 未定义。如果有人能解释一下,我不明白这种情况的区别?
$.extend
块中的 this
将引用参数中的对象,而 focus
事件处理程序中的 this
将引用引发的元素事件处理程序。
为了消除这些之间的歧义,在父对象中 this
被存储到 self
变量中,以便可以在事件处理程序中引用它。
举例说明:
$.extend(myPlugin.prototype, {
// this = the object
var self = this;
$('#foo').focus(function () {
// this = the #foo element
// self = the object
});
});