function Parent() {
this.name = "parent"
this.array = [1, 2, 3, 4]
}
function Child() {
this.age = 11
//借用父类的构造函数
Parent.call(this)
}
//把Child的原型对象指向父类的实例
Child.prototype = new Parent();
原型式继承
let person = {
name :"henry",
color:["yellow","green","blue"]
}
//创建一个方法借用空的构造函数
function Object (obj) {
function F (){}
F.prototype = obj
return new F();
}
let instance = Object(person)
寄生式继承
let person = {
name :"henry",
color:["yellow","green","blue"]
}
//创建一个方法借用空的构造函数
function Object (obj) {
function F (){}
F.prototype = obj
return new F();
}
/*
核心:在原型式继承的基础上,增强对象,返回构造函数
*/
//函数的主要作用是为构造函数新增属性和方法,以增强函数
function createObject(origin){
let clone = Object(origin)
clone.say = function (){
console.log("haha")
}
return clone
}
let instance = createObject(person)
console.log(instance.name) //henry
instance.say() //haha
寄生组合式继承
// 实现继承的核心函数
function inheritPrototype(subType,superType) {
function F() {};
//F()的原型指向的是superType
F.prototype = superType.prototype;
//subType的原型指向的是F()
subType.prototype = new F();
// 重新将构造函数指向自己,修正构造函数
subType.prototype.constructor = subType;
}
// 设置父类
function SuperType(name) {
this.name = name;
this.colors = ["red", "blue", "green"];
SuperType.prototype.sayName = function () {
console.log(this.name)
}
}
// 设置子类
function SubType(name, age) {
//构造函数式继承--子类构造函数中执行父类构造函数
SuperType.call(this, name);
this.age = age;
}
// 核心:因为是对父类原型的复制,所以不包含父类的构造函数,也就不会调用两次父类的构造函数造成浪费
inheritPrototype(SubType, SuperType)
// 添加子类私有方法
SubType.prototype.sayAge = function () {
console.log(this.age);
}
var instance = new SubType("Taec",18)
console.dir(instance)