javascript的面向对象

    技术2022-05-11  127

    方法一:

    <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)