9、面向对象(ES5、ES6)

简介: 9、面向对象(ES5、ES6)

1、ES5面向对象


ES5面向对象
构造函数 用于创建对象的函数
原型对象 proptotype
原型链 实现继承


<script>
    // 1、构造函数
    // ES5:没有类的概念,通过构造函数来实现类
    // 构造函数的函数名:首字母大写
    // 构造函数是用来创建对象用的
    function Person(name, age) {
      this.name = name;
      this.age = age;
    }
    // 2、通过构造函数的prototype属性修改属性、方法
    Person.prototype.name = 'jasmine_qiqi';
    Person.prototype.getName = function () {
      console.log(this.name);
    }
    Person.prototype.getAge = function () {
      console.log(this.age);
    }
    // 3、new创建对象
    var people = new Person('jasmine', 18);
    console.log(people.name);   // 输出结果:jasmine
    console.log(people.age);    // 输出结果:18
    people.getAge();    // 输出结果:18
    // 4、原型链(实现继承)
    // 4.1、原型
    function Female(name) {
      this.name = name;
    }
    // 4.2、原型的原型
    Female.prototype = new Person();
    // 4.3、创建对象,调用原型的原型的方法,叫做通过原型链来实现继承
    var people = new Female('jasmine_QiQi');
    people.getName();   // 输出结果:jasmine_QiQi
  </script>

2、ES6面向类


ES6面向对象
class 类,作为原型
constructor 类的构造器
extend 实现继承父类
super 继承父类构造器
  <script>
    // ES6支持类的概念
    class Person {
      constructor(name, age) {
        this.name = name;
        this.age = age;
      }
      getName() {
        console.log(this.name);
      }
      getAge() {
        console.log(this.age);
      }
    }
    var people = new Person('jasmine', 18);
    people.getName();   // 输出结果:jasmine
    people.getAge();    // 输出结果:18
    // class继承父类方法
    class Female extends Person {
      constructor(name, age, sex) {
        super(name, age);
        this.sex = sex;
      }
      getSex() {
        console.log(this.sex);
      }
    }
    var people = new Female('jasmine', 18, '女');
    people.getName();   // 输出结果:jasmine
    people.getAge();    // 输出结果:18
    people.getSex();    // 输出结果:女
    // 扩展Date的格式化方法
    Date.prototype.dateFormate = function () {
      let year = this.getFullYear();
      let month = this.getMonth() + 1;
      let date = this.getDate();
      return `${year}年${month}月${date}日`;
    }
    let today = new Date();
    var result = today.dateFormate();
    console.log(result);    // 输出结果:2022年4月7日
  </script>


相关文章
|
1月前
|
JavaScript
es5和es6的区别
es5和es6的区别
31 0
|
1月前
|
存储 JavaScript 前端开发
|
1月前
|
前端开发 JavaScript API
ES6和ES5的区别
ES6和ES5的区别
16 0
|
1月前
|
JavaScript
ES6 新特性 ES6使用 超实用
ES6 新特性 ES6使用 超实用
|
存储 JSON 安全
es学习笔记1-es概念
es学习笔记1-es概念
57 0
|
前端开发
ES5和ES6区别
ES5和ES6区别
|
前端开发 索引
ES6、ES7、ES8、ES9、ES10、ES11、ES12知识点总结(1)
ES6、ES7、ES8、ES9、ES10、ES11、ES12知识点总结(1)
ES6、ES7、ES8、ES9、ES10、ES11、ES12知识点总结(1)
|
JSON 前端开发 对象存储
ES6、ES7、ES8、ES9、ES10、ES11、ES12知识点总结(2)
ES6、ES7、ES8、ES9、ES10、ES11、ES12知识点总结(2)
ES6、ES7、ES8、ES9、ES10、ES11、ES12知识点总结(2)