用原型实现继承
- 1.原型链方式实现继承
- 2.构造函数方式实现继承
- 3.组合式继承
- 3.寄生式组合继承
一:原型链方式实现继承
Person.prototype.eating = function() {
console.log(this.name + " eating~")
}
function Student() {
this.sno = 111
}
var p = new Person()
Student.prototype = p
Student.prototype.studying = function() {
console.log(this.name + " studying~")
}
var stu = new Student()
var stu1 = new Student()
var stu2 = new Student()
stu1.name = "kobe"
console.log(stu2.name)
stu1.friends.push("kobe")
console.log(stu1.friends)
console.log(stu2.friends)
var stu3 = new Student("lilei", 112)
二:构造函数方式实现继承
function Person(name,id){
this.name = name;
this.id = id;
}
Person.prototype.eating = function(){
console.log(`${this.name}已经吃饭了`)
}
function Student(name,id,age,className){
Person.call(this,name,id);
this.age = age;
this.className = className;
}
var stu1 = new Student("lilei",12,45,"1");
console.log(stu1);
三:组合式继承
function Person(name, age, friends) {
this.name = name
this.age = age
this.friends = friends
}
Person.prototype.eating = function() {
console.log(this.name + " eating~")
}
function Student(name, age, friends, sno) {
Person.call(this, name, age, friends)
this.sno = 111
}
var p = new Person()
Student.prototype = p
Student.prototype.studying = function() {
console.log(this.name + " studying~")
}
var stu = new Student("why", 18, ["kobe"], 111)
console.log(stu)
var stu1 = new Student("why", 18, ["lilei"], 111)
var stu2 = new Student("kobe", 30, ["james"], 112)
stu1.friends.push("lucy")
console.log(stu1.friends)
console.log(stu2.friends)
三:寄生式组合继承
function createObject(o) {
function Fn() {}
Fn.prototype = o
return new Fn()
}
function inheritPrototype(SubType, SuperType) {
SubType.prototype = Objec.create(SuperType.prototype)
Object.defineProperty(SubType.prototype, "constructor", {
enumerable: false,
configurable: true,
writable: true,
value: SubType
})
}
function Person(name, age, friends) {
this.name = name
this.age = age
this.friends = friends
}
Person.prototype.running = function() {
console.log("running~")
}
Person.prototype.eating = function() {
console.log("eating~")
}
function Student(name, age, friends, sno, score) {
Person.call(this, name, age, friends)
this.sno = sno
this.score = score
}
inheritPrototype(Student, Person)
Student.prototype.studying = function() {
console.log("studying~")
}
var stu = new Student("why", 18, ["kobe"], 111, 100)
console.log(stu)
stu.studying()
stu.running()
stu.eating()
console.log(stu.constructor.name)