类,继承,原型,原型链

122 阅读1分钟

Class的运用

//创建
class person {
constructor(name,age){
this.name=name;
this.age=age;
}
sayHi(){
console.log(`hi,大家好,我的名字是 ${this.name},今年${this.age}岁`)
}
}

//实例
let xiaoming=new person('小明',15);
console.log(xiaoming.name);
console.log(xiaoming.age);   
xiaoming.sayHi();

延伸
在new的时候执行了几个步骤

Class继承

//父类
class person {
constructor(name,age){
this.name=name;
this.age=age;
}
sayHi(){
console.log(`hi,大家好,我的名字是 ${this.name},今年${this.age}岁`)
}
}

//学生子类
class student extends person{   
constructor(name,age,score){
super(name,age);
this.score=score;
}
grade(){
console.log(`我叫${this.name},成绩${this.score}`)
}
}

//老师子类  Teach继承person,老师未对age属性进行初始化,则会undefined

class Teach extends person{
constructor(name,major){
super(name);
this.major=major;
}
teach(){
console.log(`${this.name}教授 ${this.major}`)
}
}

let xiaoming=new student('小明',15,89);
console.log(xiaoming.name);
console.log(xiaoming.age);
console.log(xiaoming.score);
xiaoming.sayHi();
xiaoming.grade();



let  wls=new Teach('王老师','英语');
console.log(wls.name);
console.log(wls.major);
wls.teach();
wls.sayHi(); //sayHi 方法中年龄为undefied 

instanceof 判断类型

xiaoming instanceof person  //true 
xiaoming instanceof student //true 
xiaoming instanceof Object  //true 

扩展
instanceof的原理

原型

每个class都有prototype原型(显示原型) 每个实例都有__pro__ (隐式原型) 实例中的方法会先从自己的方法中找,如果没有则会到__proto__内找

xiaoming.__proto__===student.prototype  //true
student.prototype.sayHi     //sayHi方法
student.prototype.name     //name属性
xiaoming.__proto__.sayHi
xiaoming.__proto__.name

Student的方法指向Student.prototype中,属性如name则存在Student中,如下图

原型链

student.prototype.__proto__  
person.prototype  
person.prototype===student.prototype.__proto__

hasOwnProperty()
所有继承了 Object 的对象都会继承到 hasOwnProperty 方法。这个方法可以用来检测一个对象是否含有特定的自身属性

使用借鉴链接:developer.mozilla.org/zh-CN/docs/…

以上为纯属个人笔记记录,持续更新更改。