【问题标题】:smart javascript jquery object智能 javascript jquery 对象
【发布时间】:2013-03-04 13:51:18
【问题描述】:

嗯,我觉得这真的很有趣,当然,如果我要深入研究代码,我肯定会知道他们是如何做到的。我在说的是 JQuery 库。看看下面的代码 -

 $.prototype.mymethod=function(str){
    alert(str);
}

//now call the added method
$(document).mymethod('hello') //alert out hello

如果$是一个纯普通的javascript函数 (不使用 jquery 库),除非在 $ 之前添加 new 关键字,否则添加的方法不会按预期工作

new $(document).mymethod('hello')

但是对于 JQuery,new 关键字是非常可选的!

有人可以提供更多关于他们是如何做到这一点的见解,而无需我通过他们的图书馆吗?

编辑: 经过一番苦苦挣扎,我终于挖出了上述工作原理的实际根源机制(构建一个 JavaScript 对象 不使用new 关键词)!我相信这对于任何想要学习高级 javascript 的人来说都是一个很好的未来参考!

function a(){
    return a.prototype;
}
a.prototype.fn=function(){
    alert('hello')
}

a.prototype.test=123;

console.log(a().test)//123 
a().fn()//alerts out hello

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    来自source code

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

    当您调用$(document) 时,new 已经被调用。

    如果你想以 jQuery 的方式做同样的事情,可以这样做:

    var A = function(str){
        return new A.prototype.init(str);
    }
    A.prototype.init =function(str){
         this.str = str;
         return this;
    };
    A.prototype.init.prototype = A.prototype;
    
    A.prototype.f = function(arg){ // add your function
       console.log(this.str+' '+arg);
    };
    A('hello').f('world'); // logs "hello world"
    A('bye').f('bye'); // logs "bye bye"
    

    【讨论】:

    • @spaceman12:没有什么特别之处。只需创建一个函数,该函数在调用时会创建一个新对象并返回它。例如:function A() { return new B(); }.
    • 但是如果我想将方法​​添加到A 而不是 B,并将其称为 A().mymethod() ,您将如何为 A 返回新创建的对象?
    • 不会 A().mymethod() 调用 mymethod A 返回的任何内容,而不是 A 本身?我认为如果您想为 A 返回一个新对象,则需要 A.mymethod(),如果 mymethod 创建一个对象,它将为 A 返回一个新创建的对象...
    • @spaceman12:如果你想在不调用new 的情况下创建A 的新实例,请查看this question。请注意,这不是 jQuery 所做的。
    • @spaceman12:您的解决方案的“问题”是您总是返回相同的对象。您将无法访问作为函数传递给 a 的任何参数。
    猜你喜欢
    • 1970-01-01
    • 2013-07-26
    • 1970-01-01
    • 2012-09-10
    • 2016-10-26
    • 2013-05-18
    • 2015-07-13
    • 1970-01-01
    • 2013-08-19
    相关资源
    最近更新 更多