Lydiafly

Coder,Like JS

导航

ES5初尝试Object.create

var a = {
    init:function(){},
    play:function(){}
};
var create = (function(){
    var isES5 = !!Object.create;
    var mix = function(target, source){
        var key;
        for(key in source){
            if(source.hasOwnProperty(key)){
                target[key] = (isES5 && typeof source[key].value==='undefined')?{value:source[key]}:source[key];
            }
        }
        return target;
    };
    if(isES5){
        return function(proto, property){
            if(property){
                var p = mix({}, property);
                return Object.create(proto, p);
            }else{
                return Object.create(proto);
            }
        };
    }else{
        return function(proto, property){
            var fn = function(){}, k;
            fn.prototype = proto;
            var result = new fn();
            if(property) mix(result, property);
            return result;
        };
    }
})();
var pro = {a:1,b:2};
var b = create(a, pro);
console.dir(b);
pro = {a:{value:1}, b:{value:2}};
var c = Object.create(a, pro);
console.dir(c);

posted on 2012-06-12 10:57  lydiafly  阅读(593)  评论(0编辑  收藏  举报