一、本课目标
- 理解什么是原型链并且会使用对象继承,会画原型链图
二、继承
- 原型链
- 对象继承
2.1原型链
一个原型对象是另一个原型对象的示例:
Man.prototype = new Human();
示例:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
function Human() {
this.foot = 2;
}
Human.prototype.getFoot = function() {
return this.foot;
}
function Man() {
this.head = 1;
}
Man.prototype = new Human();
Man.prototype.getHead = function() {
return this.head;
}
var man1 = new Man();
alert(man1.getFoot());
alert(man1.getHead());
alert(man1 instanceof Man);
alert(man1 instanceof Human);
</script>
</body>
</html>
2.2Object
Object被所有的所有构造函数继承
2.3对象继承
示例代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
function Human() {
this.clothing = ["a", "b", "c"];
}
function Man() {
this.head = 1;
}
Man.prototype = new Human();
var man1 = new Man();
var man2 = new Man();
man1.clothing.push("d");
alert(man1.clothing);
alert(man2.clothing);
</script>
</body>
</html>
运行结果:
两个man对象输出的值都一样。
分析:1、一样的原因是:因为我们对应的这个Man构造函数是把所有的属性和方法共享,所以在使用的时候会把数组当中对应的一些信息做了一个共享。
2、在创建子类型的实例时,不能向父类型的构造函数中传递参数
2.4借用构造函数
示例代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
function Human() {
this.clothing = ["a", "b", "c"];
}
function Man() {
Human.call(this);
}
var man1 = new Man();
var man2 = new Man();
man1.clothing.push("d");
alert(man1.clothing);
alert(man2.clothing);
</script>
</body>
</html>
借用构造函数的一个最大优势在于可以在子类构造函数中向父类型构造函数传递参数。
示例:
示例代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
function Human(name) {
this.name = name;
}
function Man() {
Human.call(this, "Tom");
this.age = "38";
}
var man1 = new Man();
alert(man1.name);
alert(man1.age);
</script>
</body>
</html>
2.5组合继承
示例代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
function Human(name) {
this.name = name;
}
Human.prototype.getName = function() {
return this.name;
}
function Man() {
Human.call(this, "Tom");
this.age = "38";
}
Man.prototype = new Human();
Man.prototype.getAge = function() {
return this.age;
}
Man.prototype.getName = function() {//方法重写
return false;
}
var man1 = new Man();
alert(man1.getName());
alert(man1.getAge());
</script>
</body>
</html>