ES6中的class 与prototype

 一、定义构造函数  

在以前的js中,生成一个对象实例,需要先定义构造函数,然后通过prototype 的方式来添加方法,在生成实例:

      

function Person(){
       this.name = "测试"this.age = 26;
}

 Person.prototype.getName = function(){
             console.log("name:" + this.name)

}

var  p = new Person()

 

然而系现在的ES6

class Person{
     constructor(name, age){
                this.name = name;
                this.age = age;
           }
     getName() {
                return this.name;
           }
}

var p = new Person("luoqiang",26)

在ES5中原本的构造函数被constructor 替代,本来需要定义在prototype上面的,方法直接定义在class里面即可。

ES6中的类的数据类型就是函数,类本身指向构造函数,使用的时候也需要new命令。

类中所有的方法都定义在类的prototype属性上面。

 

class B {}
let b = new B();

b.constructor === B.prototype.constructor // true

 

二、Class 的静态方法

   ES6 中类有静态方法,即一个方法前加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用。

        

class Food {
static classMethod() {
   return 'hello'
}
}

Food.classMethod() // "hello"

var poo = new Food();
poo.classMethod() // TypeError: poo.classMethod is not a function

  通过类直接调用,输出的是hello,实例化以后不能调用。

  PS:

    在react、 RN中,this.state ={} 这种写法是在constructor 里面定义实例属性。

    

class ReactCounter extends React.Component {
  state;
  constructor(props){
    super(props);
     this.state = {
        count:0
  }
 }
}

    super(props)是继承父类的props 属性,state是在子类中定义实例属性。

 

三、class 继承

以前的继承方式:

function Person(name,age){
           this.name = name;
           this.age = age;
}
 Person.prototype.getName = function(){
         console.log("name:" + this.name);
}
 
 function Stu(stu_class,name,age){
         Person.call(this,name,age);
         this.stu_class=stu_class;
}
 
 Stu.prototype=new Person;
 Stu.prototype.constructors=Stu;
 Stu.prototype.getClass=function(){
        console.log("班级:" + this.stu_class)
}

// 得到一个学员信息对象

var s= new Stu()
console.log(s)

ES6的继承:

 

   class Person{
constructor(name, age){
this.name = name; this.age = age; } getName(){ return this.name; } } class Student extends Person{ constructor(stu_class,name,age){
//需注意如果一个子类继承父类,必须调用super,才能使用constructor,使用this
super(name,age)
}
getClass(){

console.log("班级:"+this.stu_class)
}
}


var p=new Person("luoqiang",26)
console.log(p)

 

注意点:

Class 定义方法是不能使用箭头函数

Class 也可以使用表达式方式声明

 

参考:https://blog.csdn.net/luoqiang0831/article/details/79641133

posted @ 2018-08-27 15:44  雪昀  阅读(6373)  评论(1编辑  收藏  举报