【问题标题】:Which form of initialization is better?哪种形式的初始化更好?
【发布时间】:2013-03-13 13:18:41
【问题描述】:

当我第一次开始编写自己的代码时,直到后来我才理解 jQuery 的“增强”初始化构造函数,所以我坚持使用不同的方式来构造我的对象。我想知道是否应该保留我的旧方法或开始使用我自己的“增强”初始化构造函数。


我的构造函数:

var $ = function(selector,context,createObj) {
        if(createObj) {
           // actually initiating object
        } else {
           return new $(selector,context,true);
        }
};

jQuery:

jQuery = function( selector, context ) {
    // The jQuery object is actually just the init constructor 'enhanced'
    return new jQuery.fn.init( selector, context, rootjQuery );
};

实际初始化:

init: function( selector, context, rootjQuery ) {
    // some code
}

改变原型(jQuery.prototype.init.prototype=jQuery.prototype):

jQuery.fn.init.prototype = jQuery.fn;

【问题讨论】:

  • 如果你也能展示替代方案会很酷。
  • 添加了jQuery的构造函数

标签: javascript jquery


【解决方案1】:

jQuery's constructor pattern 在历史上已经成长并且是不好的做法——或者至少是不必要的复杂。如果您想要一个没有new(如果应用错误)也能正常工作的构造函数,请使用

function $(selector, context) {
    if (this instanceof $) {
        // actually initiating object
    } else {
        return new $(selector, context);
    }
}

【讨论】:

  • 所以类似于 **[my code]**(stackoverflow.com/questions/23184344/…) - 您将在代码的第 3 行开始添加方法? if (this instanceof $) { this.foo=function (){...}...} ?
  • 是的,完全正确。或者你提前返回,然后在你常用的构造函数前面加上if (!(this instanceof $)) return new $(…);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-04
  • 2011-07-20
  • 2021-06-19
  • 1970-01-01
  • 2017-11-02
  • 2015-05-18
相关资源
最近更新 更多