码迷,mamicode.com
首页 > 其他好文 > 详细

ES6——Class 的基本使用

时间:2018-08-05 15:51:47      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:ons   str   cto   log   new   fun   div   对象   注意   

Class 语法。

  class 关键字声明一个类,之后以这个类来实例化对象。

  const Miaov=function(a,b){
    this.a=a;
    this.b=b;
    return this;
  }

  Miaov.prototype={
    constructor:Miaov,
    print: function(){
      console.log(this.a + ‘ ‘ + this.b);
    }
  }

  const miaov=new Miaov("hello "," world");
  miaov.print(); ///打印 hello world

 

  class Miaov{
    constructor(a,b){
    this.a=a;
    this.b=b;
    return this;
    }
  print(){
    console.log(this.a + ‘ ‘ + this.b);
    }
  }

 

//1、Miaov中的 constructor 方法是构造方法,this关键字则代表实例对象。也就是说,ES5的构造函数Miaov,对应ES6的miaov这个类的构造方法。

 

//2、miaov这个类除了构造方法,还定义了一个print 方法。注意,定义 “类” 的方法的时候,前面不需要加上function这个关键字,直接把函数 定义放进去了 就可以了。另外,方法之间不需要逗号分割,加了会报错。

 


//3、构造函数的prototype属性,在ES6 的“类” 上面继续存在。而且类的所有方法都定义在类的 prototype属性上面。

  

  console.log(Miaov.prototype);

 

 

//4、定义在类中的方法都是不可以枚举的。

 

  

  console.log(Object.keys(Miaov.prototype));

 


//5、constructoy 方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有 constructor方法,如果没有显示定义,一个控的constructor放啊会被默认添加。

class P{};

const p=new P{};

console.log(p);

 

 

以上。

ES6——Class 的基本使用

标签:ons   str   cto   log   new   fun   div   对象   注意   

原文地址:https://www.cnblogs.com/zyhbook/p/9425945.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!