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

相关推荐