当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JavaScript继承定义与用法实践分析

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

2018年08月12日  | 移动技术网IT编程  | 我要评论

unicode字符,应城天气预报,健康之路视频全集妇科

本文实例讲述了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);
    /*
    monkey:
    age: 10
    name: "codemonkey"
      __proto__: animal
      speak: function (str)
      type: "monkey"
        __proto__: animal
        constructor: function animal(t)
          __proto__: object 
*/
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');
/*
id: 1
name: "leon"
speak: function (str)
type: "human"
    __proto__: human
    constructor: function human(id,name)
      __proto__: object
*/
h.speak('hello world'); // human said hello world 
console.log(h.type); // human

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

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网