gpt4 book ai didi

Javascript this 指向最后一个对象实例

转载 作者:行者123 更新时间:2023-11-30 16:51:19 26 4
gpt4 key购买 nike

首先,抱歉我的英语不好。

我在开发的 jquery 插件的上下文中遇到问题。我在下面制作的插件的每个实例,都指向最后一个对象。示例:

var a = $("#a").EscribirConAdjuntos();
var b = $("#b").EscribirConAdjuntos();
var c = $("#c").EscribirConAdjuntos();

结果是 a 和 b 修改了 c 对象,我会尝试解释得更好,但我不知道为什么。

如果我做 a.setText("Text A");它将修改存储在 c 中的实例附加的文本区域。

(function(window, $){
var pluginName = 'EscribirConAdjuntos';
if(typeof $ === "undefined")
return console.error('No esta añadida la librería jquery.js');

var defaults = {
btnGuardar : false,
onGuardar : $.noop,
onActualizar : $.noop,
texto : false,
media : false,
};



/* Constructor principal */
var Plugin = function ($el, options){
this.o = $.extend( {}, defaults, options);
this.$.el = $el;
// I add this textarea
this.$.textarea = $('<textarea></textarea>').appendTo(this.$.el);
return this;

};
Plugin.prototype = {
$:{},
setText : function(text){
this.textarea.val(text);
}
/* Some functions */

};




$.fn[pluginName] = function(options, args){
var $this = $(this);

var plugin = $this.data(pluginName);
if(!plugin){
plugin = new Plugin($this, options);
$this.data(pluginName, plugin);
return plugin;
} else {
if(plugin[options] && typeof plugin[options] == 'function')
return plugin[options].apply(plugin,args);
else
return plugin;
}
};
})(window, jQuery);

最佳答案

问题不在于函数的 this 值。问题是 Plugin.prototype.$ 对象。 Plugin 构造函数的所有实例的 $ 属性引用同一个对象,即当您重置 eltextarea< 的值时 $ 对象的属性,它们将为所有实例重置。

> a === b
false
> a.$ === b.$
true

在构造函数中定义 $ 属性。

/* Constructor principal */
var Plugin = function ($el, options){
this.o = $.extend( {}, defaults, options);
this.$ = {};
this.$.el = $el;
// I add this textarea
this.$.textarea = $('<textarea></textarea>').appendTo(this.$.el);
return this;
};
Plugin.prototype = {
// $:{},
setText : function(text){
this.$.textarea.val(text);
}
};

关于Javascript this 指向最后一个对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30481222/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com