1-1 class定义一个简单的类
class Person{
constructor(name,age){
this.name = name;
this.age = age
}
}
直接定义在class中的属性,还是实例私有的属性。
class Person{
skill = "javascript"
constructor(name,age){
this.name = name;
this.age = age
}
}
console.log(p.hasOwnProperty("skill"))
1-2 共有方法
class Person {
constructor(name, age) {
this.name = name;
this.age = age
}
sayName(){
console.log(this.name)
}
}
var p = new Person("cheng", 18);
p.sayName()
1-3 添加共有的方法
Object.assign()
es6不支持使用直接量的方式在原型上添加
class Person {
constructor(name, age) {
this.name = name;
this.age = age
}
sayName() {
console.log(this.name)
}
}
Person.prototype = {
sayAge() {
console.log(this.age)
}
}
# 会报错
class Person {
constructor(name, age) {
this.name = name;
this.age = age
}
sayName() {
console.log(this.name)
}
}
Object.assign(Person.prototype,{
sayAge(){
console.log(this.name)
},
saySkill(){
console.log("前端")
}
})
var p = new Person("cheng",16);
p.sayAge()
1-4 继承
class Person{
constructor(name,age){
this.name = name;
this.age = age
}
sayName(){
console.log(this.name);
}
}
class Teacher extends Person{
// 类继承之后,构造函数第一行必须写super关键字,去继承父类的属性
constructor(name,age,skill){
super(name,age)
this.skill = skill
}
// 在子类的方法中调用父类的方法 (this或super去调用)
show(){
super.sayName()
// this.sayName()
}
}
var t = new Teacher("zhang",18,"js")
console.log(t);
t.sayName()