ES6——class

 class Point{
constructor(x,y){
this.x = x;
this.y = y;
}
toString(){
return this.x + this.y;
}
}
console.log(typeof Point);//function,说明类的数据类型本身就是函数,类本身指向构造函数
var a = new Point(1,2);//只有x,y,并没有constructor,__proto__中有constructor,说明类的所有方法和属性都定义在了类的prototype属性上面
console.log(a)//1,2
console.log(a.toString())//3,在类的实例上调用方法,实际上是在调用原型上的方法

//类和模块的内部,默认就是严格模式,所以不需要使用use strict指定运行模式。只要你的代码写在类或模块之中,就只有严格模式可用。
class Foo {
static classMethod() {
return 'hello';
}
}

Foo.classMethod() // 'hello'

var foo = new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function
//类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。

class Foo {
static bar () {
this.baz();
}
static baz () {
console.log('hello');
}
baz () {
console.log('world');
}
}

Foo.bar() // hello
//如果静态方法包含this关键字,这个this指的是类,而不是实例。
//上面代码中,静态方法bar调用了this.baz,这里的this指的是Foo类,而不是Foo的实例,等同于调用Foo.baz。另外,从这个例子还可以看出,静态方法可以与非静态方法重名。

class A {
constructor() {
console.log(new.target.name);
}
}
class B extends A {
constructor() {
super();//子类B的构造函数之中的super(),代表调用父类的构造函数
}
}
//super虽然代表了父类A的构造函数,但是返回的是子类B的实例,即super内部的this指的是B
new A() // A
new B() // B
posted @ 2017-11-14 19:14  六六的菜园子  阅读(116)  评论(0编辑  收藏  举报