三.其他实现方法
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:继承只是实现代码复用的方法之一。