JavaScript의 객체 지향 및 상속은 자주 사용되는 방법 및 방법입니다.
1. 전통적인 클래스 작성 방법 (ES5)
// 1. 构造函数
let Person = function({name,age,height}={}){
this.name = name ;
this.age = age ;
this.height = height ;
};
// 2. 原型添加方法
Person.prototype.showName = function(){
console.info(`${this.name} 今年 ${this.age} 岁`);
};
// 3. 创建子类,并继承
let Teacher = function({name,age,height,school}={}){
Person.call(this,{
name:name,
age:age,
height:height
});
this.school = school ;
};
// 继承父类方法
// 方式一:原型链继承
/* for(let item in Person.prototype ){
Teacher.prototype[item] = Person.prototype[item];
}*/
// 方式二:Object.create()
// Teacher.prototype = Object.create( Person.prototype );
// 方式三:调用构造函数继承
Teacher.prototype = new Person();
// 子类自己的方法
Teacher.prototype.showSchool = function(){
console.info(`我来自 ${this.school}`);
};
// 4. 创建对象
let zhangsan = new Teacher({
name : "张三",
age : 29 ,
height: "180cm",
school:"重庆工程学院"
});
zhangsan.showName(); // 调用父类方法
zhangsan.showSchool(); // 调用自己的方法
2. ES6 새 수업 작성
class Person{
//1. 构造器:内部写属性
constructor({name,age,height}){
this.name = name ;
this.age = age ;
this.height = height ;
}
//2. 添加方法
showName(){
console.info(`${this.name} 今年 ${this.age} 岁`);
}
}
// extends 继承
class Teacher extends Person{
constructor({name,age,height,school}={}){
// 继承属性。方法会通过 extends 自动继承
super({
name:name,
age:age,
height:height
});
this.school = school ;
}
//3. 添加子类自己的方法
showSchool(){
console.info(`我来自 ${this.school}`);
}
}
// 4. 创建对象
let zhangsan = new Teacher({
name : "张三",
age : 29 ,
height: "180cm",
school:"重庆工程学院"
});
zhangsan.showName(); // 调用父类方法
zhangsan.showSchool(); // 调用自己的方法
참고 : 생성자의 매개 변수는 객체 구조의 표현을 사용합니다. ES6의 해체에 대해서는이 기사 를 참조하여 ES6 해체 할당을 이해 하십시오.
ES6는 매우 편리합니다. 이제 ES6를 수용 할 때입니다.