模拟jQuery让对象内部创建的对象拥有父对象的所有属性和方法

var jQuery = function () {
    return new jQuery.prototype.init();
}
jQuery.prototype = {
    init: function () {

    },

    ceshi: function () {

        return 'dd'
    }
}

jQuery.extend = jQuery.prototype.extend = function () {
    var name, options,
        target = arguments[0] || {},
        i = 1,
        length = arguments.length;
    if (length === i) {
        target = this;
        --i;
    }
    for (; i < length; i++) {
        if ((options = arguments[i]) != null) {
            for (name in options) {
                target[name] = options[name];
            }
        }
    }
    // Return the modified object
    return target;
}

jQuery.prototype.init.prototype = jQuery.prototype;

jQuery.extend({
    min: function (a, b) {
        return a < b ? a : b;
    },
    max: function (a, b) {
        return a > b ? a : b;
    }
});
var newObj = jQuery.extend({name: 'a', age: '15'}, {name: 'd'});
console.log(newObj)
console.log(jQuery.min(2, 3))
// console.log(jQuery.min(2,3))
    

 

列子说明:

首先执行alert(jQuery().name)方法时:如果没有下面这句

jQuery.prototype.init.prototype = jQuery.prototype;

jQuery的方法new出来的对象无法获取到jQuery定义的name属性以及其他方法;

现在要想让init 构建出来的对象可以访问到jQuery定义的属性和方法。就必须将jQuery的原型对象引入赋值给init对象。

这样init对象就拥有了jQuery定义的所有的方法和属性。








posted @ 2014-04-22 23:49  开水中的糖  阅读(251)  评论(0编辑  收藏  举报