<script type="text/javascript"> var child={}; var mother={ name:"zhangzhiying", lastAge:21, sex:"女"}; function extend(target,source){ for(var p in source){ target[p]=source[p]; } return target; } extend(child,mother); console.log(child); //<STRONG>Object {name: "zhangzhiying", lastAge: 21, sex: "女"}</STRONG> </script> 2、使用for in来循环遍历原型对象的属性,然后一一赋值给我们的空对象,从而实现了“继承”。这个思路很正确,下面我们来对以上示例进行改造:<script type="text/javascript"> var child={}; var mother={ name:"zhangzhiying", lastAge:21, <STRONG>set age(value){ this.lastAge=value; }, get age(){ return this.lastAge+1; },</STRONG> sex:"女"};<BR> <STRONG> mother.age=15;</STRONG>//有set方法,具有可写性 function extend(target,source){ for(var p in source){ target[p]=source[p]; } return target; } extend(child,mother); console.log(child);//<STRONG>Object {name: "zhangzhiying", lastAge: 15, age: 16, sex: "女"}</STRONG> </script>可以看到代码中使用了一对set,get;其中age是一个存取器属性。<script type="text/javascript"> var child={}; var mother={ name:"zhangzhiying", lastAge:21, set age(value){ this.lastAge=value; }, get age(){ return this.lastAge+1; }, sex:"女"}; Object.defineProperty(mother,"lastAge",{writable:false}); //把lastAge设置成了不可写 mother.age=15; //设置无效,因为lastAge的值不变,所以lastAge+1不变,即age不变 function extend(target,source){ for(var p in source){ target[p]=source[p]; } return target; } extend(child,mother); console.log(child); //Object {name: "zhangzhiying", lastAge: 21, age: 22, sex: "女"} child.lastAge=12; //结果显示lastAge改变,说明child.lastAge没有“继承”到mother.lastAge的特性,我们再用getOwnPropertyDesriptor()方法确认一下<BR> console.log(Object.getO<EM id=__mceDel></script> </EM>结论:要实现继承,我们还需要解决的问题->“继承”属性特性。
<script type="text/javascript"> var child={}; var mother={ name:"zhangzhiying", lastAge:21, set age(value){ this.lastAge=value; }, get age(){ return this.lastAge+1; }, sex:"女"}; Object.defineProperty(mother,"lastAge",{writable:false}); mother.age=15; <SPAN style="COLOR: #333399"><STRONG>function extend(target,source){ var names=Object.getOwnPropertyNames(source);//获取所有的属性名 for(var i=0;i<names.length;i++){ if(names[i] in target) continue;//如果这个属性存在,就跳过(原型继承中,如果自有属性和原型对象的属性重名,保留自有属性) var desc=Object.getOwnPropertyDescriptor(source,names[i]);//获取mother属性的描述符对象(即属性特性的集合,es5中用描述符对象来表示) Object.defineProperty(target,names[i],desc);//将mother的描述符对象给child的属性定义 } return target; }</STRONG></SPAN> extend(child,mother); console.log(child); child.lastAge=12; console.log(Object.getOwnPropertyDescriptor(child,"lastAge")); console.log(child); </script>最后的结果:
可以明显看到三次的打印,child“继承”到了set和get,lastAge数值没发生变化,writable也是false了。
总结:最近在看《javascript权威指南》,总结一点心得,有错误欢迎指正,共同学习进步~
以上这篇javascript 用函数实现继承详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。