在ES6中,class (类)经过 class 关键字定义类。它能够被看做一个语法糖,让对象原型的写法更加清晰、更像面向对象编程的语法。
类其实是个“特殊的函数”,就像你可以定义的函数表达式和函数声明同样,类语法有两个组成部分:类表达式和类声明。编程
class Person{
constructor(x,y){
this.x = x;
this.y = y
}
}函数
总结:this
函数声明和类声明之间的一个重要区别是函数声明会提高,类声明不会。须要先进行声明,再去访问,不然会报错prototype
var person= new Person() class Person { constructor(x, y) { this.x = x this.y = y } } // Personis not defined
类必须使用 new 调用,不然会报错code
class Person { constructor(x, y) { this.x = x this.y = y } } Person() // TypeError Class constructor Person cannot be invoked without 'new'
类表达式能够是被命名的或匿名的对象
* 匿名类 */ let Person = class { constructor(x, y) { this.x = x this.y = y } } /* 命名的类 */ let Person = class Person { constructor(x, y) { this.x = x this.y = y } }
constructor 方法是类的默认方法,在new 命令生成对象实例时,会自动调用constructor方法,同时默认返回实列对象的this;原型
一个类必须有 constructor 方法,若是没有显式定义,一个空的 constructor 方法会被默认添加。一个类只能拥有一个名为 “constructor” 的特殊方法,若是类包含多个 constructor 的方法,则将抛出 一个 SyntaxError 。it
class Person { constructor(x, y) { this.x = x // 默认返回实例对象 this this.y = y } toString() { console.log(this.x + ', ' + this.y) } }
在类对象的内部的方法【constructor除外】前面加上static后,该方法就是静态方法了io
注意:静态方法能够经过类名调用,不能经过实例对象调用,不然会报错console
class Person { static sum(a, b) { console.log(a + b) } } var p = new Person() Person.sum(1, 2) // 3 p.sum(1,2) // TypeError p.sum is not a function
class Person { constructor() { // 默认返回实例对象 this } sum() { } toString() { console.log('123456') } } // 给 Person 的原型添加方法 Person.prototype.toVal = function() { console.log('I am is toVal') } // 等同于 Person.prototype = { constructor() {}, sum() {}, toString() {} } var p = new Person() p.toString() // 123456 p.toVal() // I am is toVal Person.toString() // TypeError Person.toStringis not a function Person.toVal() // TypeError Person.toVal is not a function
实例方法也能够经过实例对象调用,但一样不能经过类名调用,会报错
class Person { constructor() { this.sum = function(a, b) { console.log(a + b) } } } var p = new Person() p.sum(1,2) // 3 Person.sum(1,2) // TypeError Person.sum is not a function