zoukankan      html  css  js  c++  java
  • es6中class类的全方面理解(一)

    ES6 中的Class

     阅读约 4 分钟

    基本用法

    ES5 的写法

    function Point(x, y) {
      this.x = x;
      this.y = y;
    }
    
    Point.prototype.toString = function () {
      return '(' + this.x + ', ' + this.y + ')';
    };
    
    var p = new Point(1, 2);

    ES6 的写法

    class Point {
      constructor(x, y) {
        this.x = x;
        this.y = y;
      }
    
      toString() {
        return '(' + this.x + ', ' + this.y + ')';
      }
    }

    在类的实例上面调用方法,其实就是调用原型上的方法。

    class B {}
    let b = new B();
    
    b.__proto__.constructor === B.prototype.constructor?console.log("true"):console.log("false")
    console.log(typeof b.__proto__.constructor)
    console.log(typeof B.prototype.constructor)

    clipboard.png

    注:类的内部所有定义的方法,都是不可枚举的

    constructor 方法

    constructor方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor方法,如果没有显式定义,一个空的constructor方法会被默认添加。
    注意点

    • constructor方法默认返回实例对象(即this),完全可以指定返回另外一个对象。

      class Foo {
        constructor() {
          return Object.create(null);
        }
      }
      
      new Foo() instanceof Foo
      // false
    • 类必须使用new调用,否则会报错。

      class book{
          constructor(){
              this._year=2004;
              this.edition=1;
          }
          get year(){
              return this._year;
          }
          set year(newVal){
              if(newVal>2004){
                  this._year=newVal;
                  this.edition+=newVal-2004;
              }
          }
      }
      let b=new book();
      b.year = 2004; //2
      console.log(b.edition);

    取值函数(getter)和存值函数(setter)

    class book{
        constructor(){
            this._year=2004;
            this.edition=1;
        }
        get year(){
            return this._year;
        }
        set year(newVal){
            if(newVal>2004){
                this._year=newVal;
                this.edition+=newVal-2004;
            }
        }
    }
    let b=new book();
    b.year = 2004; //2
    console.log(b.edition);
     
  • 相关阅读:
    【题解】P2262 [HNOI2004]FTP服务器
    关于大模拟
    CodeForces 666E Forensic Examination
    Bzoj3233 [Ahoi2013]找硬币
    Bzoj4350 括号序列再战猪猪侠
    UOJ#31 【UR #2】猪猪侠再战括号序列
    UOJ#21 【UR #1】缩进优化
    51nod1667 概率好题
    [CodeChef
    51nod1245 Binomial Coefficients Revenge
  • 原文地址:https://www.cnblogs.com/sexintercourse/p/12269454.html
Copyright © 2011-2022 走看看