将非严格模式JQuery3.3模态函数转为严格模式并支持链式调用
解决严格模式下Modal函数链式调用兼容问题
首先得说清楚你遇到的问题根源:旧代码是构造函数模式,每次调用_modale()都会生成一个新的实例,所有方法都返回this(当前实例),所以能实现链式调用;而你改成对象字面量后,这变成了一个单例对象,而且很多方法没有返回自身(比如pre()直接返回数值,不是对象),同时部分方法还错误地引用了全局变量而非实例状态,导致链式调用失效。
下面是符合严格模式规范、兼容jQuery3.3且保留链式调用能力的修改方案:
'use strict'; var num_modali = 0; function _modale() { // 确保用new关键字调用,严格模式下避免全局污染 if (!(this instanceof _modale)) { return new _modale(); } // 初始化实例状态 this.livello_m = num_modali; // 获取目标路径的jQuery对象(兼容jQuery3.3) this.percorso = function() { return this.livello_m > 0 ? $('body').find('#modale_' + this.livello_m).find('.modale_content') : $('body'); }; // 获取记录列表选择器 this.listaRecord = function() { // 注意:这里要用实例的livello_m,不是全局num_modali return this.livello_m > 0 ? '#lista_records_modale' : '#lista_records'; }; // 层级减1,返回自身实现链式调用 this.pre = function() { this.livello_m--; return this; }; // 返回最终路径的jQuery对象 this.go = function() { return this.percorso(); }; // 获取当前层级 this.getlivello = function() { return this.livello_m > 0 ? this.livello_m : 0; }; // 关闭模态框,返回自身 this.chiudi = function() { modale.destroyModale(); // 假设modale是全局的销毁对象 return this; }; // 删除指定元素,返回自身 this._delete = function(what) { this.percorso() .find(this.listaRecord()) .find(what) .remove(); // jQuery3.3中remove()不需要传参数 return this; }; }
关键修改要点:
- 开启严格模式:开头添加
'use strict';,符合严格模式规范,避免意外的全局变量、this指向错误等问题。 - 保留构造函数模式:继续使用构造函数生成实例,确保每次调用
_modale()都创建独立的实例,状态不会互相干扰。 - 所有修改状态的方法返回
this:pre()、chiudi()、_delete()这些方法最后都返回this,保证链式调用的连续性。 - 修正状态引用错误:
listaRecord()方法改为引用实例的livello_m,而不是全局的num_modali,确保每个实例的状态独立。 - 兼容jQuery3.3:
percorso()中保留jQuery的链式查找逻辑,remove()方法去掉冗余参数(jQuery3.3中remove()不需要传入选择器)。 - 确保构造函数调用安全:添加
if (!(this instanceof _modale))判断,即使忘记用new关键字调用,也能生成正确的实例。
现在你就可以正常使用链式调用了:
// 示例调用 _modale().pre().pre().go();
内容的提问来源于stack exchange,提问作者Robert
相关产品推荐
相关产品推荐

