2013-03-15 58 views
1

嗯,我觉得这很有趣,当然,如果我想深入了解这些代码,我肯定会知道他们是如何做到的。我在说的是JQuery库。看看下面的代码 -智能javascript 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 关键字)的实际根源的机制!我相信这将成为任何渴望学习advanved 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 

回答

3

source code

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

new,当你调用$(document)已经调用。

如果你想要做同样的事情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" 
+0

@ spaceman12:没有什么特别的地方。只需创建一个函数,该函数在被调用时创建一个新对象并将其返回。例如:'function A(){return new B(); }'。 – 2013-03-15 18:38:35

+0

但是,如果我想将方法​​添加到'A'而不是B,并将其称为A()。mymethod(),那么您将如何返回新创建的A对象? – spaceman12 2013-03-15 18:47:02

+0

对于A而不是A返回的内容,'A()。mymethod()'不会调用'mymethod'吗?我想你想为A返回一个新的对象,你需要'A.mymethod()',如果'mymethod'创建一个,它将返回一个新创建的对象... – ckersch 2013-03-15 18:56:31