智能javascript jquery对象

智能javascript jquery对象,javascript,jquery,Javascript,Jquery,嗯,我觉得这真的很有趣,当然,如果我深入研究代码的话,我肯定知道他们是如何做到这一点的。我说的是JQuery库。请看下面的代码- $.prototype.mymethod=function(str){ alert(str); } //now call the added method $(document).mymethod('hello') //alert out hello 如果$是纯正常的javascript函数 (不使用jquery库),除非在$ new $(documen

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

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

//now call the added method
$(document).mymethod('hello') //alert out hello
如果
$
是纯正常的javascript函数 (不使用jquery库),除非在
$

new $(document).mymethod('hello')
但是对于JQuery,
new
关键字是非常可选的

有人能在我不必翻阅他们的图书馆的情况下,对他们是如何做到这一点提供更多的见解吗

编辑: 经过一番艰苦的努力,我终于找到了上述工作的实际根本机制(构建一个 JavaScript对象 不使用新的

关键字)!我相信这将作为一个很好的未来参考任何人希望学习先进的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
从:

当您调用
$(文档)
时,已调用
新的

如果您想用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"

@宇航员12:这没有什么特别的。只需创建一个函数,该函数在调用时创建一个新对象并返回它。例如:
函数A(){return new B();}
。但是如果我想将方法添加到
A而不是B,并将其作为A().mymethod()调用,您将如何为A返回新创建的对象?不会对A返回的任何对象而不是A本身调用
mymethod
?我想如果你想返回一个新对象,你需要
a.mymethod()
,它将返回一个新创建的对象,如果
mymethod
创建了一个…@spaceman12:如果你想创建
a
的新实例而不调用
new
,请查看。请注意,jQuery并不是这样做的。@spaceman12:解决方案的“问题”在于总是返回同一个对象。您将无法访问作为函数传递给
a
的任何参数。
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"