繁体   English   中英

如何从其他脚本访问实例 object?

[英]How can I access an instance object from other script?

我有两个脚本: scipt1.js:

(function ($) {
    'use strict';

    var A = function (element, options) {
        this.element = $(element);
     
    };

    A.prototype.update = function update() {}
       
    $.fn.doA = function (option) {
        return this.each(function test() {
                newA = new A(this, options);
            }

           
        });
    };

}(jQuery));

和来自斜坡html的 scipt2.js:

    $( document ).ready(function(){
                    $('#$this->id').doA($javascriptParameterString);
                    });    

在 $( document ).ready(function().. from script2.js 中,我想在执行 doA 后从 scipt1.js 调用 function 更新。无论如何我可以引用实例 newA 并调用 function 更新吗?

使用.data将调用doA的元素与实例相关联,然后.data可以在其他地方使用来检索它。

 var A = function(element, options) { this.element = $(element); this.options = options; }; $.fn.doA = function(options) { return this.each(function test() { $(this).data('a', new A(this, options)); }); }; // Other script: $(document).ready(function() { $('.foo').doA({ property: 'foo' }); console.log('now iterating over instantiated As:'); for (const foo of $('.foo')) { const a = $(foo).data('a'); console.log(a.options); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="foo"></div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM