首页 > 学院 > 开发设计 > 正文

浅谈JS继承(三)

2019-11-08 00:44:18
字体:
来源:转载
供稿:网友

三.其他实现方法

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

//shallow copyfunction extend(parent,child) { var i; child=child||{}; for(i in parent){ if(parent.hasOwnPRoperty(i)){ child[i]=parent[i]; } } return child;}//deep copyfunction 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());//errorvar 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!undefinedvar 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!Tomvar 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:继承只是实现代码复用的方法之一。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表