jQuery中对象的构建

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery</title>
    <script src="jquery.js"></script>
</head>
<body>
<div id="aaron">jQuery</div>

<script type="text/javascript">

    (function(window, factory){
        factory(window);
    }(typeof window !== undefined ? window : this, function(window, noGlobal){
        var $jQuery = function(selector, context){
            return new $jQuery.fn.init( selector, context );
        }
        $jQuery.fn = $jQuery.prototype = {
            init: function(){
                this.name = "aa";
                return this;
            },
            constructor: $jQuery
        }
        if(typeof noGlobal === "undefined"){
            window.$jQuery = $jQuery;
        }
        return $jQuery;
    }))
    var a = $jQuery();
    show(a.name);
    function show(data) {
        jQuery("body").append('<li>' + data + '</li>')
    }

</script>
</body>
</html>

 

分离构造器

http://www.imooc.com/code/3398

var $$ = ajQuery = function(selector) {
        this.selector = selector;
        return this
    }
    ajQuery.fn = ajQuery.prototype = {
        selectorName:function(){
            return this.selector;
        },
        constructor: ajQuery
    }
    var a = new $$('aaa');  //实例化
    console.log(a);
    var name =  a.selectorName();//aaa //得到选择器名字
    console.log(name);
改进,去掉new
ar $$ = ajQuery = function(selector) {
        console.log(this);
        if(!(this instanceof ajQuery)){
            return new ajQuery(selector);
        }
        this.selector = selector;
        return this;
    }
    ajQuery.fn = ajQuery.prototype = {
        selectorName:function(){
            return this.selector;
        },
        constructor: ajQuery
    }
    var a = $$('aaa');  //实例化
    console.log(a);
    var name =  a.selectorName();//aaa //得到选择器名字
    console.log(name);

 

posted @ 2016-01-06 10:30  darr  阅读(301)  评论(0编辑  收藏  举报