ECMAScript6之class————呱呱二号

{
//1、constructor 类的构造函数
//构造函数是类的默认方法,通过new命令生成对象实例,
//如果类中没有显式声明constructor,会生成一个空的constructor方法
class Person{
constructor(name="guaguaerhao"){
this.name = name;
}
}
}
{
//2、类的实例对象
class Person{
constructor(name="guaguaerhao"){
this.name = name;
}
}
//实例化对象,并传递传参数
let person = new Person('fa');
console.log(person);
}
{
//3、类的继承
//父类
class Parent{
constructor(name,age){
this.name = name;
this.age = age;
}
}
//继承父类 Parent
//子类冰箱
class Child extends Parent{
//如果子类中有constructor,必须先调用父类的构造函数
//super中传入参数,可以覆盖父类构造函数中的参数
constructor(name,age){
super(name,age);
}
}
let child = new Child('名称1',18);
console.log(child);
}
{
//4、Class表达式
//不过Me不是这个类的名称,MyClass才是这个类的名称,
//而Me只能在类的内部中使用,指代当前类
const MyClass = class Me{
constructor(name='me'){
this.name = name;
}
static getClassName () {
return Me.name;
}
}
}
{
//5、另外类的定义不存在变量提升
// new Foo(); //会报错
class Foo{
constructor(name='guaguaerhao'){
this.name = name;
}
getName (){
return this.name;
}
}
}
{
//6、私有方法和私有属性
//不过ES6并没有提供,只能用变通的方法模拟实现
//一、命名上加以区别,
// 缺点:外部还是可以访问
//二、利用Symbol值得唯一性,将私有方法的名字命名为一个Symbol的值

//一
class Person{
//公有方法
getName (){
return this.name;
}
//私有方法
_getAge () {
return this.age;
}
}

//二
const bar = Symbol('bar');
const snaf = Symbol('snaf');

class Company{
//公有方法
foo(baz){
this[bar](baz);
}
//私有方法
[bar](baz){
return this[snaf] = baz;
}
}
}
{
//7、this的指向
//类的方法内部如果含有this,它默认指向类的实例
class Person{
printName (name = 'seven'){
return this.name = name;
}
}
}
{
//8、name属性
class Person1{}
Person1.name; //Person
console.log(Person1.name,'类的名称');
}
{
//9、Class的取值函数(getter)和存值函数(setter)
class MyClass {
constructor(name = 'guaguaerhao') {
this.name = name;
}

get longName() {
return this.name + 'haha';
}
set longName(value){
this.name = this.name + 'hehe';
}
}
let myClass = new MyClass();
myClass.longName; //guaguaerhaohaha
myClass.longName = 'fafa';
console.log(myClass.longName); //fafahehe
}
{
//10、Class中的静态方法
class Test{
constructor(){

}
static getName (){
// return this.age; //这样返回时不对的,
return '我叫呱呱二号';
}
}
//静态方法的使用,直接用类名调用方法
console.log(Test.getName()); //
}
{
//11、静态属性
//不好意思ES6中没有提供
//但是难不倒强大的程序员
class Fruit{
static getName(){
return '呱呱二号'
}
}
//直接在类的外部写
Fruit.fruitName = 'apple'; //静态属性,就是这么吊
}
{
//好了,就这么多了,缺的,自己去
// http://es6.ruanyifeng.com 传送门
}
posted @ 2018-01-02 23:18  呱呱二号  阅读(190)  评论(0编辑  收藏  举报