栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

JavaScript继承定义与用法实践分析

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaScript继承定义与用法实践分析

本文实例讲述了Javascript继承定义与用法。分享给大家供大家参考,具体如下:

javascript 继承 , 老生长谈的东西, 大家应该都很熟悉了, 平时工作基本不会直接使用, 这段时间不忙, 所以补习了下相关基础知识 ,自己动手实践, 加深理解:

基类定义如下:

// base class
function Animal(t)
{
   if(typeof t==='string')
    this.type=t;
   else
   {
    if(t)
      this.type=t.toString();
    else
      this.type='Animal'
   }
   this.speak=function(str)
   {
    if(str)
      console.log(this.type+' said '+str);
    else
      throw "please specify what you want to say!";
   }
}

1. 原型继承 (javascript 类库本身基于原型继承)

String, Number , Boolean 这三大原始类型 我们可以很直接的通过prototype 检查到他们继承自Object.

Date, RegExp ,Array 这三应该是间接继承了Object, 他们的prototype属性很特殊 :

Date.prototype =Invalid Date
RegExp.prototype=/(?:)/
Array.prototype=[]

原型继承代码如下: (可以看到Mokey 原型链上的Animal和Object)

// Monkey : Animal 
function Monkey(name,age)
{
   this.name=name;
   this.age=age;
}
Monkey.prototype=new Animal('Monkey');
// Example 01
var m=new Monkey('codeMonkey',10);
    
console.log(m.type); // Monkey
console.log(m.name); // codeMonkey
console.log(m.age); // 10
m.speak('hello world') // Monkey said hello world 

2. 调用父类构造函数 ( 通过传递子类的this指针 , 将原本是父类的公开成员直接添加到了子类中,从子类原型链中无法看出继承关系)

// Human:Animal 
function Human(id,name)
{
    // call base class's constuctor function
   Animal.call(this,'Human');
   this.id=id;
   this.name=name;
}
var h=new Human(1,'leon');

h.speak('hello world'); // Human said hello world 
console.log(h.type); // Human

更多关于Javascript相关内容感兴趣的读者可查看本站专题:《javascript面向对象入门教程》、《Javascript错误与调试技巧总结》、《Javascript数据结构与算法技巧总结》、《Javascript遍历算法与技巧总结》及《Javascript数学运算用法总结》

希望本文所述对大家Javascript程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/80853.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号