浅析jQuery的基础设计模式

来源:互联网 发布:笔记本usb端口上的电涌 编辑:程序博客网 时间:2024/05/18 03:44
jQuery虽说已不像之前如此流行,但是jQuery本身的精髓却是每个前端人都需要去领悟的。

今天,后生也想尝试着去理解jQuery整套框架的设计模式和精要。那么就先从jQuery的设计模式开始说起吧。

使用jQuery非常方便,我们可以这样做
$(‘#id’).html();
还可以这样做
$(‘#id’).html().css();

从上面两个非常简单的例子里,我们需要思考的是:jQuery是怎么实现构造的,jQuery又是如何实现链式调用的。因为,jQuery就是在这么一个模式下建立起来的。

剔除掉其他一些代码,实现上面功能de代码片段其实很简洁,但却不简单。
varjQuery = function( selector, context ){    return new jQuery.fn.init( selector, context );}jQuery.fn = jQuery.prototype = {};jQuery.fn.init = function(selector, context){ return this; };jQuery.fn.init.prototype = jQuery.fn;

乍一看,完全不知道在干嘛。我们还是得通过一步一步的分析来理解它。

首先,写个小例子。
var Kingsley = function(){    this.name =“Kingsley”;    this.age = 23;}Kingsley.prototype.sayHello = function(){    console.log(“PHP is the best programming language in the world”);}var kings = new Kingsley();console.log(kings.name);

上面无非就是用JS实现了一个构造函数。通过构造函数来创建一个实例。
那么,要实现像jQuery一样,不通过new就实例化了一个对象,可以尝试通过直接返回的方式来达到目的。

于是又写了个小例子
var Kingsley = function(){    return new Kingsley();};

OMG~难产了。死循环。
那咋整呢?

于是又思考了下,通过在原型上添加一个init函数,每次new的时候给它一个新的对象。OK,试试看。。。
var Kingsley = function(){    return new Kingsley.prototype.init();}Kingsley.prototype.init = function(){    this.name = “Kingsley”;    return this;}Kingsley.prototype.sayHello = function(){    console.log("PHP is the best programming language in the world");}var kings = Kingsley();console.log(kings.name);//Kingsleykings.sayHello();//error

出事故了。。。取到了name,却没有取到原型上的sayHello。非常明显,现在this的指向并不是Kingsley的实例而是init的实例对象。那么要怎么才能又能访问init作用域又能访问原型作用域呢?

那就是,
Kingsley.prototype.init.prototype = Kingsley.prototype;

吆喝,这可真够绕的呢。


最后看看最终版本:
var jQuery = function( selector, context ){    return new jQuery.fn.init( selector, context );}jQuery.fn = jQuery.prototype = {        init : function( selector, context){        this.name = "PHP";        return this;    },    sayHello:function(){        console.log("PHP is the best programming language in the world");        return this; //链式调用    },    sayGoogBye:function(){        console.log("Hello World");        return this;    }    }//MOST IMPORTANTjQuery.fn.init.prototype = jQuery.fn;//Object { init: init(), sayHello: sayHello(), sayGoogBye: sayGoogBye() }var jquery = jQuery();console.log(jquery.name);//PHPjquery.sayHello();//PHP is the best programming language in the worldjquery.sayHello().sayGoogBye();

每次return this 相当于又返回了自身对象,这也就是为什么能够实现链式调用的原理。

到这里,加上之前的文章介绍过的extend方法和noconflict方法,也就构成了jQuery最基本的设计模式。


原创粉丝点击