1)(每一个类都是函数数据类型的)每一个函数都会自带一个属性prototype(原型),而且这个属性的值是一个对象数据类型的,浏览器为其开辟了一个堆内存,这个堆内存中存放的就是全部公有的属性和方法
2)在函数的prototype属性的堆内存中,浏览器为其增长了一个属性constructor,指向当前函数自己
3)(实例和函数的prototype也是对象数据类型的) 每个对象数据类型也有一个自带的属性__proto__,指向当前所属类的原型es6
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
复制代码
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中的继承会继承实例、原型和静态方法bash
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('小猫');
复制代码