js 中内置了一个window对象。
window对象上有一些方法(构造函数)。
例如 Object() Array() Function()
同时这些方法都有一个自己的原型对象。如
Object.prototype={}
Array.prototype={}
当我们使用这些构造函数来new一个实例的时候。
我们写
obj1=new Object()
此时 obj1是一个对象,它有一些方法例如toString().
那么这些方法是哪来的呢。
原来
obj1.proto=Object.prototype.
那么这叫做继承吗?
new 关键字做了一些什么?
继承实际上是类与类之间的关系。它使得子类具有父类的属性和方法。
反过来说,一个类A拥有了类B的属性和方法,则可以说对象A继承了对象。
js在es5的时候没有类,它是使用原型链来模拟继承。
对于一个js对象来说,它默认会有一个proto的属性。指向它构造函数的prototype属性。
class Parent {
[x: string]: any;
constructor(name:string,age:string) {
this.name=name;
this.age=age;
}
show(){
console.log(this.name+"---"+this.age);
}
}
class Son extends Parent{
constructor(name:string,age:string,hight:string) {
super(name,age);
this.name=name;
this.hight=hight;
}
say(){
console.log(this.name+"---"+this.age+"--"+this.hight);
}
}
const son1= new Son("小明","18岁","180cm");
son1.show();
son1.say();
console.log("Son",Son);
console.log("Son.__proto__ === Parent",Son.__proto__ === Parent); // true
console.log("Son.prototype",Son.prototype.__proto__ === Parent.prototype); //true
function Parent(name:string,age:string,weight:string) {
console.log("运行Parent");
console.log(name,age,weight);
this.name = name;
this.age = age;
this.weight = weight;
}
Parent.prototype.show=function(){
console.log(`名字:${this.name},年龄:${this.age},体重:${this.weight} `)
};
function Son(name:string,age:string,height:string) {
(Parent as any).call(this,name,age,"40kg");
console.log("运行到Son");
this.name = name;
this.age = age;
this.height = height;
}
Son.prototype = Object.create(Parent.prototype);
Son.prototype.constructor=Son;
Son.prototype.say=function(){
console.log(`名字:${this.name},年龄:${this.age},身高:${this.height} `)
};
// Son.prototype.__proto__ = Parent.prototype;
const son1=new (Son as any)("儿子一","8岁","160cm");
son1.say();
son1.show();
console.log("son1",son1);
image.png