原型链,es5 构造函数
1)(每个类都是函数数据类型的)每个函数都会自带一个属性prototype(原型),并且这个属性的值是一个对象数据类型的,浏览器为其开辟了一个堆内存,这个堆内存中存放的就是所有公有的属性和方法
2)在函数的prototype属性的堆内存中,浏览器为其增加了一个属性constructor,指向当前函数本身
3)(实例和函数的prototype也是对象数据类型的)
每一个对象数据类型也有一个自带的属性__proto__,指向当前所属类的原型
function Animal(name){
this.name=name;
}
//公有属性
Animal.prototype.info={time:'100'}
let animal1=new Animal('哺乳类');
let animal2=new Animal('哺乳类');
console.log(animal1.__proto__==Animal.prototype);
console.log(animal1.__proto__.construtor==Animal);
console.log(Animal.prototype.__proto__==Object.prototype);
console.log(Object.prototype.__proto);//null
es5类的继承
1)继承实例上的属性 2)继承公共属性 3)继承公有和私有属性
function Animal(name){
this.name=name;
}
Animal.prototype.info={time:'100'}
function Cat(name){
Animal.call(this,name)//1)继承实例上的属性
}
2)继承公共的属性
Cat.prototype.__proto__=Animal.prototype;//原型链继承
原理:如果Cat原型上没有,则会通过__proto__指向Animal.prototype,则会找到animal公共属性。并且如果Cat原型上修改的话也不会影响Animal的原型
Object.setPrototypeOf(Cat.prototype, Animal.prototype);//es6把上面的方法进行了改写,也是继承公共属性
let cat=new Cat('小花花');
console.log(cat.info);
console.log(cat.name);
Cat.prototype=Object.create(Animal.prototype,{constructor:{value:Cat}})//继承公共属性
//Object.create的原理:
function create(parentPrototype) {
function Fn() {} // 创建一个空类
Fn.prototype = parentPrototype;
return new Fn(); // 创建的实例则只有父类公共方法
}
3)继承公有和私有属性
call+原型继承
4)不推荐->父(私有+公有) 变为 子(公有)
function A(val) {
this.x = 100;
this.xy=val
}
A.prototype.getX = function () {
console.log(this.x);
};
function B() {
this.y = 200;
}
//想让B作为子类,继承A这个父类中的私有的/公有的属性和方法
B.prototype = new A;
var b = new B("nihao");
b.getX();
console.log(b.xy);//undefined 缺点:不能传参给父类
es6继承
es6中的继承会继承实例、原型和静态方法
class Animal{ // es6只支持静态的方法,并不支持静态属性 Animal.a = 1; es7支持
static a(){
return 1;
}
constructor(val){
this.name=val;
this.age=9;
}
eat(){
console.log('吃饭');
}
}
let animal=new Animal('动物');
class Cat extends Animal{
//不传参的话可以不写constructor
constructor(name){//用constructor则必须使用super
super(name)
}
//super虽然代表了父类Animal的构造函数,但是返回的是子类Cat的实例
}
let cat=new Cat('小猫');