YUI的mix方法

YUI有一个mix方法:
Applies the supplier's properties to the receiver. By default all prototype and static propertes on the supplier are applied to the corresponding spot on the receiver. By default all properties are applied, and a property that is already on the reciever will not be overwritten. The default behavior can be modified by supplying the appropriate parameters.
这个方法可以使receiver接受supplier的属性和方法。默认情况下supplier上面的原型和静态属性会应用到receriver相应的属性上面,默认情况所有的属性都会被接受,receiver上面已有属性不会被覆写。
YUI.mix(r,s,ov,wl,mode,merge);
主要的和最常用的参数是r和s两个
r是receiver
s时supplier
ov是一个对象,标识要要覆盖的属性
wl是一个白名单,
mode是覆盖的模式
merge是一个布尔值,标示是否要对属性对象也做合并
看看里面的几种覆盖时如何实现的

Y.mix = function(r, s, ov, wl, mode, merge) {
    if (!s || !r) {
        return r || Y;
    }
//根据模式来判断,默认是Obj to Obj的
    if (mode) {
        switch (mode) {
            case 1: // proto to proto
                return Y.mix(r.prototype, s.prototype, ov, wl, 0, merge);
            case 2: // object to object and proto to proto
                Y.mix(r.prototype, s.prototype, ov, wl, 0, merge);
                break; // pass through
            case 3: // proto to static
                return Y.mix(r, s.prototype, ov, wl, 0, merge);
            case 4: // static to proto
                return Y.mix(r.prototype, s, ov, wl, 0, merge);
            default:  // object to object is what happens below
        }
    }

    // Maybe don't even need this wl && wl.length check anymore??
    var i, l, p, type;
//白名单如果有值,就对白名单里面的属性进行合并,如果有ov,那么就
    if (wl && wl.length) {
        for (i = 0, l = wl.length; i < l; ++i) {
            p = wl[i];
            type = Y.Lang.type(r[p]);//看具体的属性是什么类型的
            if (s.hasOwnProperty(p)) {//如果这个属性是p自己的
                if (merge && type == 'object') {//如果设定了merge并且属性是一个对象,那么就调用mix本身,把s[p]的属性加到r[p]上面
                    Y.mix(r[p], s[p]);
                } else if (ov || !(p in r)) {//如果允许ov或者r里面没有p,那么就在r里面加上p这个属性
                    r[p] = s[p];
                }
            }
        }
    } else {//如果没有wl
        for (i in s) {//遍历s里面的属性
            if (s.hasOwnProperty(i)) {//如果i是s本身的属性,就按规则合并属性
                if (merge && Y.Lang.isObject(r[i], true)) {
                    Y.mix(r[i], s[i], ov, wl, 0, true); // recursive
                } else if (ov || !(i in r)) {
                    r[i] = s[i];
                }
            }
        }

        if (Y.UA.ie) {//如果时IE,做一个修正。
            _iefix(r, s);
        }
    }

    return r;
};


_iefix = function(r, s) {
    var fn = s.toString;
    if (Y.Lang.isFunction(fn) && fn != Object.prototype.toString) {
        r.toString = fn;
    }
};


ie不会枚举javascript对象上面的native属性,即便这个属性被重写过。
YUI的_iefix对toString做了一个处理。

你可能感兴趣的:(JavaScript,prototype,IE,yui)