コアJavaScript第7章第2部(ES 5 ES 6)


ES5

 	var ES5 = function(name){
        	this.name = name;
        };
        ES5.staticMethod = function(){
        	return this.name + ' staticMethod';
        };
        ES5.prototype.method = function(){
        	return this.name + ' method';
        }
        var es5Instance = new ES5('es5');
        console.log(ES5.staticMethod());	//ES5 staticMethod
        console.log(es5Instance.method());	//es5 method

ES6

 	var ES6 = class{
        	constructor (name){
        		this.name = name;
        	}
        	static staticMethod(){
        		return this.name + ' staticMethod';
        	}
        	method = function(){
        	return this.name + ' method';
        	}
        }

        var es6Instance = new ES6('es6');
        console.log(ES6.staticMethod());	//ES6 staticMethod
        console.log(es6Instance.method());	//es6 method
ES 5のコンストラクタ=>ES 6のクラスにおけるコンストラクタ
ES 5の方法=>ES 6の静的方法
ES 5の原型.メソッド=>ES 6のプロトタイプメソッド

クラス継承(ES 6)

var Rectangle = class{
  constructor(width, height){
    this.width = width;
    this.height = height;
  }
  getArea(){
    return this.width * this.height;
  }
};

var Square = class extends Rectangle{
  constructor(width){
    super(width,width);
  }
  getArea(){
    console.log('size is:',super.getArea());
  }
};
活動場所を表す
let square = new Square(10);
square.getArea();
「中華人民共和国環境保護法」を施行した結果、size is: 100となった.
以前の内容のように、classを使わなければ、何に接続しても、何もしなくてもいいです.

ソース


コアJavaScript