Skip to content

Instantly share code, notes, and snippets.

@GeekaholicLin
Last active December 9, 2016 14:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GeekaholicLin/d29bc87611a5c0b1650165438d8824f0 to your computer and use it in GitHub Desktop.
Save GeekaholicLin/d29bc87611a5c0b1650165438d8824f0 to your computer and use it in GitHub Desktop.
jQuery instantiation
在跟着视频一起阅读jQuery的2.0.3源码的时候,发现一个'有意思'的地方,或者说巧妙的地方。
css()等方法是在jQuery原型属性`prototype`的下面定义的,比如jQuery.prototype.css = function(){//do sth.}
但是,我们在调用css()方法的时候,首先使用`$()`[也就是`jQuery()`]获取到一个元素对象,从而调用,例如`$('#top').css();`。但是在源码当中,
当调用jQuery()的时候其实拿到的是init()构造函数的实例。而不是jQuery()构造函数的实例。【因为是jQuery()构造函数的实例,才会向上搜素到该实例的原型对象中的css()等方法】
```javascript
jQuery = function( selector, context ) {
return new jQuery.fn.init( selector, context, rootjQuery );
}//返回init()构造函数的实例
```
我们只要让Init()构造函数的实例也变成jQuery()构造函数的实例,那问题就迎刃而解了~
**那在jQuery中是怎么设计的?** ==> **让两个构造函数的prototype属性为相同对象!!!**
在line 96 处,`jQuery.fn = jQuery.prototype`,说明`fn`与`prototype`是等价的,都是jQuery构造函数的原型属性。
接下来一句代码,最重要的一点。
> `jQuery.fn.init.prototype = jQuery.fn;`
这么复杂,如何分析?
其实,这句代码等同于:
> `jQuery.prototype.init.prototype = jQuery.prototype;`
也就是说,init构造函数的实例对象(假设为j)`var j = new jQuery.fn.init( selector, context, rootjQuery );`的`_proto_`属性指向jQuery构造函数的`prototype`属性,
也就是**j其实也是jQuery构造函数的实例对象**。
或者从内存/对象引用的角度分析,init()构造函数`jQuery.prototype.init`的`prototype属性`和jQuery()构造函数的`prototype属性`为相同的对象。
为何要这么麻烦?
说到底,还是为了封装,为了更好地进行取值。每次调用`$()`时都会进行初始化`new jQuery.fn.init( selector, context, rootjQuery );`,而这初始化
之后的不同实例对象,依然可以共同使用同一个方法,也就是挂载在其构造函数的`prototype`属性上的方法。
---
update:
补充图片
![prototype](https://www.processon.com/chart_image/584abdf5e4b005d48b7d2c40.png)
PS:刚接触继承和prototype,错误之处还望指出~
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment