JS——原型(prototype)和原型链
JS中的继承问题,它的本质是使用JavaScript中的原型来实现的,其中constrcutor是构造函数。
class People{
constructor(name){
this.name=name;
}
study(){
console.log("study");
}
}
class Teacher extends People(){
constructor(name,age){
super(name);
this.age=age;
}
introduce(){
console.log(`我是${this.name},今年${this.score}岁`);
}
}
class Student extends People(){
constructor(name,sex){
super(name);
this.sex=sex;
}
introduce(){
console.log(`我是${this.name},${this.sex}`);
}
}
const student =new Student("beryl","女");
console.log(student );
student .introduce();
const teacher =new Teacher("beryl",19);
console.log(teacher);
teacher.introduce();
构造函数中为什么要使用原型?
- 构造函数方法很好用,但是存在浪费内存的问题。
原型
问答:
- 原型是什么? 一个对象,也称prototype为原型对象
- 原型的作用是什么? 共享方法
构造函数原型prototype
- 构造函数通过原型分配的函数是所有对象所共享的
- Javascript规定,每一个构造函数都有一个prototype属性,指向另一个对象。注意这个prototyoe就是一个对象,这个对象的所有属性和方法,都会被构造函数所拥有。
- 可以把那些不变的方法,直接定义在prototype对象上,这样所有对象的实例就可以共享这些方法。
function anmals(eat,drink){
this.eat=eat;
this.drink=drink;
}
animals.prototype.say=function(){
console.log("hello");
}
var cat=new animals("猫粮","水");
var dog=new anlmals("狗粮","水");
cat.sing();
dog.sing();
对象原型__ proto __
- __ proto __ 对象原型和原型对象prototype是等价的。
- 对象会有一个属性__ proto __ 指向构造函数的prototype原型对象,之所以我们对象可以使用构造函数prototype原型对象的属性的方法,就是因为对象有__ proto __ 原型的存在。
- 对象身上系统自己添加一个__ proto __ 指向我们的构造函数的原型对象
- 方法say()的查找机制:首先看cat对象上是否有say()方法,如果有就执行这个对象上的say()。如果没有,因为有__ proto __ 的存在,就去构造函数原型对象prototype身上去查找say()这个方法。
- __ proto __ 对象原型的意义就在于为对象的查找机制提供一个方向,或者说是一条路线,但是它是一个非标准属性,因此在实际开发中,不可以使用这个属性,它只是内部指向原型对象prototype
constructor 构造函数
- 对象原型(__ proto __ )和构造函数(prototype)原型对象里面都有一个constructor属性,constructor我们称为构造函数,因为它指回构造函数本身。
- constructor主要用于记录该对象引用于哪个构造函数,它可以让原型对象重新指向原来的构造函数。
- 通常情况下,我们需手动指回原来的构造函数
function anmals(eat,drink){
this.eat=eat;
this.drink=drink;
}
animals.prototype={
//如果我们修改了原来的原型对象,给原型对象赋值的是一个对象,则必须手动的利用constructor指会原来的构造函数。
constructor:animals;
say:function(){
console.log("hello");
},
sing:function(){
console.log("sing");
}
}
var cat=new animals("猫粮","水");
var dog=new anlmals("狗粮","水");
cat.sing();
dog.sing();
原型 原型对象 实例之间的关系
原型链
- 只要是对象就有__ proto __ 的存在
- Anlmals原型对象中的__ proto __ 指向的是Object原型对象prototype,故Animals.prototype.__ proto __ ===Object.prototype 为true
- 而Object原型对象也是一个对象,故也有__ proto __ 的存在,Object原型对象中的__ proto __ 指向的是NULL。
不是生产知识,只是知识的搬运工。若有不对的地方,请大家指正,谢谢!
博客地址:BerylYing