JQuery框架设计过程演示

来源:互联网 发布:intouch2016软件下载 编辑:程序博客网 时间:2024/05/14 10:54

假设现在有一个Person类,模拟JQuery的实现过程

阅读前要复习下javascript的作用域和原型继承等知识点

第一阶段:需要实现调用构造器时得到一个Person实例,可以读取Person的属性和方法

function display(content) {document.write(content + "<br/>");}var $ = Person = function(name) {return new Person(name);};Person.fn = Person.prototype = {//constructor : Person,name : "steve",sayHello : function() {display("Hello World I am " + this.name);}};

 

从代码中已经可以看到存在很大的问题就是循环引用,调用$("jack").sayHello()浏览器肯定会陷入死循环,所以代码需要修改一下

 

var $ = Person = function(name) {return Person.fn.init(name);};Person.fn = Person.prototype = {//constructor : Person,init : function(name) {this.name = name;this.sayName = function() {display("My name is " + this.name);};return this;},name : "steve",sayHello : function() {display("Hello World I am " + this.name);}};

 

这里就巧妙地运用了Person.fn这个对象,可能会被这些相同名字的对象搞混,其实Person.fn就是Person的原型Person.prototype。

现在运行测试代码$("jack").sayHello()和$("jack").sayName()就能运行成功。

需要指出的时两次调用$("jack")都是实现同一个原型的实例,这虽然很“省内存”,但是会因为共享属性造成意想不到的结果,看下面的例子

var $ = Person = function(name) {return Person.fn.init(name);//return new Person.fn.init(name);};Person.fn = Person.prototype = {constructor : Person,init : function(name) {this.name = name;this.sayName = function() {this.count++;display("My name is " + this.name);};return this;},name : "steve",count : 0,sayHello : function() {this.count++;display("Hello World I am " + this.name);},getCount : function() {display("Count=" + this.count);}};$("jack").sayHello();$("").getCount();$("marry").sayName();$("").getCount(); 

 

这里添加了一个count属性来监控函数调用,由于共享一个原型,所以得到的结果为

Hello World
Count=1
My name is marry
Count=2

第二阶段:实现每次调用都有独立的对象,互不干扰,此时就要用到new关键词,以对象方式生成Person.fn.init的原型实例,而不是调用函数(构造器)获得对象。

此时init这个function就要object化了,直接加个new会出错,需要将init的原型指向Person的原型(或Person.fn)。如果理解”javascript中函数就是对象,对象就有原型“这句话相信这个很容易就理解,源代码如下:

var $ = Person = function(name) {return new Person.fn.init(name);};Person.fn = Person.prototype = {constructor : Person,init : function(name) {this.name = name;this.sayName = function() {this.count++;display("My name is " + this.name);};return this;},name : "steve",count : 0,sayHello : function() {this.count++;display("Hello World I am " + this.name);},getCount : function() {display("Count=" + this.count);}};Person.fn.init.prototype=Person.fn;$("jack").sayHello();$("").getCount();$("marry").sayName();$("").getCount(); 

运行结果

Hello World
count=0
My name is marry
Count=0


理解了这个例子的演化过程就基本深刻理解了JQuery的架构设计的核心思想了!


0 0
原创粉丝点击