JavaScript为对象原型prototype添加属性的两种方式
代码如下:
<script type="text/javascript"> <!-- /* 给原型 prototype 添加属性的两种方式 */ //方式一 var myObj = function(){ this.study = "JavaScript"; } myObj.prototype.hobby = function() { this.hobby = "See girl"; } var newObj = new myObj(); for ( var attr in newObj ) { document.write( attr +"<br/>" ); } document.write( "==================== <br/>" ); //方式二 var superObj = { name:"xugang" }; var subObj = { age:20 }; function extend(superObj,subObj){ //获得父对象的原型对象 subObj.getSuper = superObj.prototype; //将父对象的属性给子对象 for(var i in superObj){ subObj[i] = superObj[i]; } } extend(superObj,subObj); for ( var s in subObj ) { document.write( s +"<br/>" ); //遍历子对象的属性 } //--> </script>
运行结果:
hobby
study
====================
age
getSuper
name
相关推荐
zrtlin 2020-11-09
xuebingnan 2020-11-05
wikiwater 2020-10-27
heheeheh 2020-10-19
Crazyshark 2020-09-15
softwear 2020-08-21
ZGCdemo 2020-08-16
jczwilliam 2020-08-16
littleFatty 2020-08-16
idning 2020-08-03
jinxiutong 2020-07-26
lanzhusiyu 2020-07-19
Skyline 2020-07-04
xiaofanguan 2020-06-25
Aveiox 2020-06-23
dragonzht 2020-06-17