第一种: 原型链的方式
function Parent(name){
this.name=name;
}
Parent.prototype.say=function(){
console.log('saying');
}
function Child(name,age){
this.name = name;
this.age=age;
}
Child.prototype = new Parent();
Child.prototype.constructor=Child;//修复
var c1= new Child('Tom',18);
console.log(c1);
console.log(c1.name,c1.age);
console.log(Child.prototype.constructor);
第二种: 借用构造函数
function Parent(name) {
this.name =name;
}
function Child(name,age) {
Parent.call(this);
this.age = age;
}
var c1= new Child('Tom',18);
console.log(c1.name,c1.age);
第三种: 组合继承
function Parent(name) {
this.name = name;
this.walk=function(){
console.log('waking~~~');
}
}
Parent.prototype.say = function () {
console.log('saying~~~');
}
function Child(name, age) {
Parent.call(this,name,age);
this.age = age;
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;//修复
var c1 = new Child('Tom', 18);
console.log(c1.name, c1.age);
c1.say()
第四种: 寄生式组合继承 ----最完美的继承的方法
function Parent(name) {
this.name = name;
this.walk = function () {
console.log('waking~~~');
}
}
Parent.prototype.say = function () {
console.log('saying~~~');
}
function Child(name, age) {
Parent.call(this, name, age);
this.age = age;
}
Child.prototype = Object.create(Child.prototype);
Child.prototype.constructor = Child;//修复
//在这里增加新方法
var c1 = new Child('Tom', 18);
console.log(c1.name, c1.age);
c1.say()
第五种: 寄生式继承 ---了解即可
function createAnother(original) {
var clone = Object.create(original); //通过调用函数创建一个新对象
clone.sayHi = function () { //以某种方式来增强这个对象
alert("Hi");
};
return clone; //返回这个对象
}
var person = {
name: "Bob",
friends: ["Shelby", "Court", "Van"]
};
var anotherPerson = createAnother(person);
anotherPerson.sayHi();
// anotherPerson是基于person创建的一个新对象,新对象不仅具有person的所有属性和方法,还有自己的sayHi()方法。