JavaScrip中如何实现继承
Java中实现继承通过关键字extands来实现的,而javascrip中没有该关键字,通过以下方法可以实现继承关系:
先定义一个父类
//定义一个动物类
function Animal(name){
this.name=name || 'Animal';
this.sleep=function(){
document.write(this.name+'正在睡觉');
}
}
//原型方法
Animal.prototype.eat=function(food){
document.write(this.name+'吃:'+food);;
}
原型链继承
父类对象是可以直接访问父类的属性和方法的,那么可以通过把父类对象赋给子类原型,那么子类对象就拥有了父类原型中的所有原型和方法。
//原型链继承
function Cat(){}
Cat.prototype=new Animal();
Cat.prototype.name='Cat';
var cat= new Cat();
document.write(cat.name);
document.write('<br>');
document.write(cat.sleep());
document.write('<br>');
document.write(cat.eat('fish'));
document.write('<br>');
document.write(cat instanceof Animal);
document.write('<br>');
document.write(cat instanceof Cat);
document.write('<hr>');
输出结果为:
// Cat
// Cat正在睡觉
// Cat吃:fish,
// true
// true
缺点:1.无法实现多继承
2.来自原型对象的引用属性是所有实例共享的
3.创建子类实例时,无法向父类构造函数进行传参
实例继承
为父类实例添加新特性,作为子类返回实例
//实例继承
function Dog(name){
var instant=new Animal();
instant.name='dog';
return instant;
}
var dog=new Dog();
document.write(dog.name);
document.write('<br>');
document.write(dog.sleep());
document.write('<br>');
document.write(dog.eat('gutou'));
document.write('<br>');
document.write(dog instanceof Animal);
document.write('<br>');
document.write(dog instanceof Dog);
document.write('<hr>');
输出结果为:
// dog
// dog正在睡觉
// dog吃:gutou
// true
// false
缺点:实例是父类的实例,不是子类的实例,通过输出结果false就可以看出。
拷贝继承
获取到父类实例,子类拷贝父类已经存在的可枚举的属性或者方法。
//拷贝继承
function Tiger(name){
var animal=new Animal();
for (var t in animal) {
Tiger.prototype[t]=animal[t];
}
Tiger.prototype.name=name || 'tiger';
}
var tiger=new Tiger();
document.write(tiger.name);
document.write('<br>');
document.write(tiger.sleep());
document.write('<br>');
document.write(tiger.eat('ji'));
document.write('<br>');
document.write(tiger instanceof Animal);
document.write('<br>');
document.write(tiger instanceof Tiger);
document.write('<br>');
输出结果为:
// tiger
// tiger正在睡觉
// tiger吃:ji
// false
// true
缺点:1.效率低,内存占用高
2.无法获取父类不可枚举的方法(不可枚举的方法不能进行for in语句访问到)
for in
该语句为JavaScript中的一个循环语句;这个循环语句是用来循环一个对象的属性;
例如:循环输出location对象中的属性名称
<script type="text/javascript">
document.write("location对象中的的属性");
document.write("<br>");
for (var s in location) {
document.write(s);
document.write("<br>");
}
输出结果为:
location对象中的的属性
hash
host
hostname
href
origin
pathname
port
protocol
search
assign
reload
replace
toString
JavaScript中 instanceof的使用
instanceof用于判断一个变量是否为某个对象的实例。
如果我们判断一个对象是否为数组:
var arr = new Array();
document.write(arr instanceof Array);
document.write('<br>')
document.write(arr instanceof Object);
document.write('<br>')
输出结果为:
// true
// true
判断一个对象是否为另一个对象的实例:
function test() {}
var a = new test();
document.write(a instanceof test);
document.write('<br>')
输出结果为:
// true