浅谈JS继承(三)

三.其他实现方法

1.通过复制属性实现继承

//shallow copy
function extend(parent,child) {
    var i;
    child=child||{};
    for(i in parent){
        if(parent.hasOwnProperty(i)){
            child[i]=parent[i];
        }
    }
    return child;
}

//deep copy
function extendDeep(parent,child) {
    var i,
        toStr=Object.prototype.toString,
        astr='[object Array]';

    child=child||{};

    for(i in parent){
        if(parent.hasOwnProperty(i)){
            if(typeof parent[i]=="object"){
                 child[i]=(toStr.call(parent[i])===astr)?[]:{};
                extendDeep(parent[i],child[i]);
            }else{
                child[i]=parent[i];
            }
        }
    }
    return child;
}

//混入 mix-in 获得具有所有源对象属性的新对象
function mix(){
    var arg,prop,child={};
    for(arg=0;arg<arguments.length;arg++){
        for(prop in arguments[arg])
        if(arguments[arg].hasOwnProperty(prop)){
            child[prop]=arguments[arg][prop];
        }
    }
    return child;
}

2.借用方法

1.call() apply()

var one={
    name:'Amy',
    say:function (greet) {
        return greet+"!"+this.name;
    }
};
console.log(one.say("hi")); // "hi!Amy"
// console.log(say());//error
var two={
    name:"Tom"
};
console.log(one.say.apply(two,['hello']));//"hello!Tom"

2.绑定
将方法和对象绑定起来,然后返回另一个函数

var one={
    name:'Amy',
    say:function (greet) {
        return greet+"!"+this.name;
    }
};
var two={
    name:"Tom"
};

var say=one.say;
console.log(say("haha"));//haha!undefined

var another={
    name:"otherObject",
    method:function (callback) {
        return callback('Bye');
    }
};

console.log(another.method(one.say));//Bye!undefined

//绑定函数
function bind(obj,method) {
    return function () {
        return method.apply(obj,[].slice.call(arguments))
    }
}

var twosay=bind(two,one.say);
console.log(twosay('yoyo'));//yoyo!Tom

var other=bind(another,one.say);
console.log(another.method(other));//Bye!otherObject

绑定所需要的代价就是:额外闭包的开销

ECMAScript中将bind()方法添加到了Function.prototype,使得bind()就像apply()和call()一样简单易用。
var newFunc=obj.someFunc.bind(myobj,1,2,3)

PS:继承只是实现代码复用的方法之一。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值