JavaScript继承定义与用法实践分析
本文实例讲述了JavaScript继承定义与用法。分享给大家供大家参考,具体如下:
javascript继承,老生长谈的东西,大家应该都很熟悉了,平时工作基本不会直接使用,这段时间不忙,所以补习了下相关基础知识,自己动手实践,加深理解:
基类定义如下:
//baseclass
functionAnimal(t)
{
if(typeoft==='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"pleasespecifywhatyouwanttosay!";
}
}
1.原型继承(javascript类库本身基于原型继承)
String,Number,Boolean这三大原始类型我们可以很直接的通过prototype检查到他们继承自Object.
Date,RegExp,Array这三应该是间接继承了Object,他们的prototype属性很特殊:
Date.prototype=InvalidDate RegExp.prototype=/(?:)/ Array.prototype=[]
原型继承代码如下:(可以看到Mokey原型链上的Animal和Object)
//Monkey:Animal
functionMonkey(name,age)
{
this.name=name;
this.age=age;
}
Monkey.prototype=newAnimal('Monkey');
//Example01
varm=newMonkey('codeMonkey',10);
/*
Monkey:
age:10
name:"codeMonkey"
__proto__:Animal
speak:function(str)
type:"Monkey"
__proto__:Animal
constructor:functionAnimal(t)
__proto__:Object
*/
console.log(m.type);//Monkey
console.log(m.name);//codeMonkey
console.log(m.age);//10
m.speak('helloworld')//Monkeysaidhelloworld
2.调用父类构造函数(通过传递子类的this指针,将原本是父类的公开成员直接添加到了子类中,从子类原型链中无法看出继承关系)
//Human:Animal
functionHuman(id,name)
{
//callbaseclass'sconstuctorfunction
Animal.call(this,'Human');
this.id=id;
this.name=name;
}
varh=newHuman(1,'leon');
/*
id:1
name:"leon"
speak:function(str)
type:"Human"
__proto__:Human
constructor:functionHuman(id,name)
__proto__:Object
*/
h.speak('helloworld');//Humansaidhelloworld
console.log(h.type);//Human
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《javascript面向对象入门教程》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》
希望本文所述对大家JavaScript程序设计有所帮助。