Javascript指向最后一个对象实例

Javascript this point to last object instance

本文关键字:一个对象 实例 最后 Javascript      更新时间:2023-09-26

首先,对不起我的英语不好。

我正在开发的jquery插件的上下文有问题。我在下面创建的每个插件实例,都指向最后一个对象。示例:

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

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

如果我做了.setText("文本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);
    }
};