简单的javascript 继承机制

本文介绍了一种在JavaScript中实现对象扩展和继承的方法,通过自定义`extend`方法来增强对象的功能,并展示了如何使用该方法实现两个类之间的继承关系及方法覆盖。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <title>Untitled Document</title>
  6. </head>
  7. <body>
  8. <script type="text/javascript">
  9. Object.extend = function(destination, source){  //为Object对象添加一个 “对象扩展” 的静态方法
  10.     for(var p in source){
  11.         destination[p] = source[p]
  12.     }
  13.     return destination;
  14. }
  15. Object.prototype.extend = function(object){   
  16.     return Object.extend.apply(this, [this,object])  //利用Object类的静态方法为每个object对象添加 “扩展”的方法
  17. }
  18. function class1(){
  19.     this.name = 'jack'
  20. }
  21. class1.prototype = {
  22.     method : function(){
  23.         alert(this.name);
  24.     }
  25. }
  26. function class2(){
  27.     this.name = 'mike'
  28. }
  29. class2.prototype = (new class1()).extend({
  30.     method2 : function(){
  31.         alert('hello ' + this.name) 
  32.     }
  33. })
  34. var a = {
  35.     name : 'sco'
  36. }
  37. var b = {};
  38. b.extend(a);
  39. alert(b.name);   // sco
  40. var obj = new class2();
  41. obj.method();  // mike
  42. obj.method2();  // hello mike
  43. alert(obj instanceof class2);  // true
  44. alert(obj instanceof class1);   // true
  45. </script>
  46. </body>
  47. </html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值