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里面即可。

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的继承:

猜你喜欢

转载自www.cnblogs.com/leyan/p/9542623.html