ES6中的class

class类

ES5造类

function Person(name, age) {
      this.name = name
      this.age = age
    }
    Person.prototype.sayName = function () {
      return this.name
    }
    let p1 = new Person('张三', 28)
    console.log(p1);
    console.log(p1.sayName());

ES6造类

1.简单造类

class Person {
      //实例化的收获会立即被调用
      constructor(name, age) {
        this.name = name
        this.age = age
      }
      sayName() {
        return this.name
      },
      sayAge() {
        return this.age
      }
    }
    let p2 = new Person('张三', 28)
console.log(p2.sayName(),p2.sayAge(),p2.name,p2.age)

2.继承和父类方法的重写

继承(继承父类的属性和方法)
class Animal {
      constructor(name, age) {
        this.name = name
        this.age = age
      }
      sayName() {
        return this.name
      }
      sayAge() {
        return this.age
      }
    }
    class Dog extends Animal {
      constructor(name, age, color) {
        super(name, age)
        // 相当于Animal.call(this, name, age)
        this.color = color
      }
      sayColor() {
        return `${this.name}今年${this.age}岁了,他是一条${this.color}色的狗`
      }
      //重写父类方法
      sayName() {
        return this.sayColor() + `这是重写的方法`
      }
    }
let dog = new Dog('小黄', 28, 'black')
console.log(dog.sayName(),dog.sayAge(),dog.name,dog.age);

3.get,set和Object.assign()

class Person {
      //实例化的收获会立即被调用
      constructor(name, age) {
        this.name = name
        this.age = age
      }
    //获取值的get方法
      get name() {
        console.log('价格属性被读取了');
        return 'yes'
      }
    //设置值的set方法
      set name(newVal) {
        console.log('价格属性被修改了');
      }
    }
    let p2 = new Person('张三', 28)
    //通过Object.assign()方法一次性向类中添加多个方法
    Object.assign(Person.prototype, {
      sayName() {
        return this.name
      },
      sayAge() {
        return this.age
      }
    })
    console.log(p2.name);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值