javascript的面向对象

方法一:

<html>
<script type="text/javascript">
function user(){}
user.prototype.name = "保密";
user.prototype.age = "保密";
user.prototype.shout = function (){return "你们好,我的朋友!";}
user.prototype.produce = function (){return "我的名字:"+new user().name + "/n   我的年纪:"+new user().age;}

function userA(){}
userA.prototype = new user();
userA.prototype.name = "张三"; 
userA.prototype.shout = function (){return "大伙好啊";}

function userB(){}
userB.prototype = new user();
userB.prototype.name = "李四";
userB.prototype.age = "20";
userB.prototype.shout = function(){return "哥们好啊";}
userB.prototype.produce = function(){return "我是" + new userB().name}

function d(user){
 alert("1:" + user.shout()+"/n" + "2:" + user.produce() + "/n" + "name:" + user.name + " and age:" + user.age);
}
</script>

<body>

<button οnclick="d(new userA())">UserA</button>
<button οnclick="d(new userB())">UserB</button>
</body>
</html> 

方法二:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE></TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function user(){
 var name;
 var age;
 this.setName = function(n){
  name = n;
 }
 this.getName = function(){
  return name;
 }
 this.setAge = function(a){
  age = a;
 }
 this.getAge = function(){
  return age;
 }
 this.shout = function(){
  return "welcome!!!";
 }
}
function userPerson(){
 this.shout = function(){
  return "I love you";
 }
}
function createInheritance(parent,child){
 var property;
 for(property in parent){
  if(!child[property]){
   child[property] = parent[property];
  }
 }
}
function d(user){
 return user.getName() + "/n" + user.getAge() + "/n" + user.shout();
}
function showUserPerson(){
 var p = new userPerson();
 createInheritance(new user(),p);
 p.setName("Tom");
 p.setAge("20");
 alert(d(p));
}
//-->
</SCRIPT>
</HEAD>

<BODY>
<INPUT TYPE="submit" οnclick="showUserPerson()">
</BODY>
</HTML>

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值