您的位置:首页 > Web前端 > JavaScript

js--继承

2016-04-17 16:07 555 查看
js继承一般分为3种办法,一种是es5基于原型的继承以及es5的call( ),一种是es6基于类继承

// 使用JavaScript继承机制,实现两个类之间的继承。
// 父类:人,属性:年龄、身高、性别。方法:行走、行走、睡觉。
// 子类:学生,属性:年级、学分。方法:上学、放学、休学。
// 目标,创建子类学生的实例,调用行走、吃饭、睡觉、上学、放学、休学6个方法。

【基于原型继承】

        //es5实现继承[基于原型继承]
function Person(age,height,sex){
this.name=name;
this.age=age;
this.height=height;
this.sex=sex;
this.go=function(){
console.log("行走")
};
this.eat=function(){
console.log("行走")
};
this.sleep=function(){
console.log("睡觉")
};
}

function Student(nj,sc){
this.nj=nj;
this.sc=sc;
this.goSchool=function(){
console.log("上学")
}
this.bybySchool=function(){
console.log("放学")
}
this.overSchool=function(){
console.log("休学")
}
}

Student.prototype=new Person();
var stu=new Student(2,30);
stu.go();
stu.sleep();
stu.goSchool();
stu.bybySchool();
stu.overSchool();


【call( )、apply( )】
说简单一点,这两函数的作用其实就是更改对象的内部指针,即改变对象的this指向的内容。这在面向对象的js编程过程中有时是很有用的。
两个函数基本相同,唯一的区别是,后者可以接受多个参数,即参数可以数组
func.call(func1,var1)对应的apply写法为:func.apply(func1,[var1,var2,var3])。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script type="text/javascript">
//类式继承:利用JS中的call()和apply()方法
function Animal(){
this.name = "Animal";
this.showName = function(){alert(this.name);}
}
function Cat(){this.name = "Cat";}

var animal = new Animal();
var cat = new Cat();

//通过call或apply方法,将原本属于Animal对象的showName()方法交给对象cat来使用了。
animal.showName.call(cat,","); //animal.showName.apply(cat,[]);
</script>
</body>
</html>




<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script type="text/javascript">
function Animal(name){
this.name = name;
this.showName = function(){
alert(this.name);
}
}

function Cat(name){
Animal.call(this, name);
}

var cat = new Cat("Black Cat");
cat.showName();
/*Animal.call(this) 的意思就是使用 Animal对象代替this对象,
* 那么 Cat中不就有Animal的所有属性和方法了吗,
* Cat对象就能够直接调用Animal的方法以及属性了.*/
</script>
</body>
</html>




【基于类继承】

       //es6实现继承[基于类继承]
class Person{
constructor(age,height,sex){
this.age=age;
this.height=height;
this.sex=sex;
}
go(){
console.log("行走")
};
eat(){
console.log("行走")
};
sleep(){
console.log("睡觉")
};
}

class Student extends Person{
constructor(nj,sc){
super()
this.nj=nj;
this.sc=sc;
}
goSchool(){
console.log("上学")
}
bybySchool(){
console.log("放学")
}
overSchool(){
console.log("休学")
}
}
var stu=new Student(2,30);
stu.go();
stu.sleep();
stu.goSchool();
stu.bybySchool();
stu.overSchool();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: