<!DOCTYPE html>
<html>
<head>
<title>继承的三种方式</title>
</head>
<body>
<script type="text/javascript">
/*
// 原型继承
// 父类
function Person(name,age) {
this.name = name;
this.age = age;
}
// 父类原型对象属性
Person.prototype.id = 001;
Person.prototype.sayName = function() {
alert(this.name);
}
// 子类
function Boy(sex) {
this.sex = sex;
}
// 继承已经实现
Boy.prototype = new Person('z3');
var b1 = new Boy('男');
alert(b1.name); // z3
alert(b1.id); // 1
alert(b1.sex); // 男
// 原型继承的特点:既继承了父类的模板,又继承了父类的原型对象
*/
/* // 使用构造函数继承 : 之继承模板,不继承原型对象
// 父类
function Person(name,age) {
this.name = name;
this.age = age;
}
// 父类原型对象属性
Person.prototype.id = 001;
Person.prototype.sayName = function() {
alert(this.name);
}
// 子类
function Boy(name, age, sex) {
Person.call(this, name, age);
this.sex = sex;
}
var b1 = new Boy('z3',20,'男');
alert(b1.name); // z3
alert(b1.id); // undefined
alert(b1.sex); // 男
*/
// 混合使用原型继承和构造函数继承方法
// 父类
function Person(name,age) {
this.name = name;
this.age = age;
}
// 父类原型对象属性
Person.prototype.id = 001;
Person.prototype.sayName = function() {
alert(this.name);
}
// 子类
function Boy(name, age, sex) {
Person.call(this, name, age);
this.sex = sex;
}
// 子类的原型对象是父类实例对象
Boy.prototype = new Person();
var b1 = new Boy('z3',20,'男');
alert(b1.name); // z3
alert(b1.id); // 1
alert(b1.sex); // 男
</script>
</body>
</html>
<html>
<head>
<title>继承的三种方式</title>
</head>
<body>
<script type="text/javascript">
/*
// 原型继承
// 父类
function Person(name,age) {
this.name = name;
this.age = age;
}
// 父类原型对象属性
Person.prototype.id = 001;
Person.prototype.sayName = function() {
alert(this.name);
}
// 子类
function Boy(sex) {
this.sex = sex;
}
// 继承已经实现
Boy.prototype = new Person('z3');
var b1 = new Boy('男');
alert(b1.name); // z3
alert(b1.id); // 1
alert(b1.sex); // 男
// 原型继承的特点:既继承了父类的模板,又继承了父类的原型对象
*/
/* // 使用构造函数继承 : 之继承模板,不继承原型对象
// 父类
function Person(name,age) {
this.name = name;
this.age = age;
}
// 父类原型对象属性
Person.prototype.id = 001;
Person.prototype.sayName = function() {
alert(this.name);
}
// 子类
function Boy(name, age, sex) {
Person.call(this, name, age);
this.sex = sex;
}
var b1 = new Boy('z3',20,'男');
alert(b1.name); // z3
alert(b1.id); // undefined
alert(b1.sex); // 男
*/
// 混合使用原型继承和构造函数继承方法
// 父类
function Person(name,age) {
this.name = name;
this.age = age;
}
// 父类原型对象属性
Person.prototype.id = 001;
Person.prototype.sayName = function() {
alert(this.name);
}
// 子类
function Boy(name, age, sex) {
Person.call(this, name, age);
this.sex = sex;
}
// 子类的原型对象是父类实例对象
Boy.prototype = new Person();
var b1 = new Boy('z3',20,'男');
alert(b1.name); // z3
alert(b1.id); // 1
alert(b1.sex); // 男
</script>
</body>
</html>