之前小编对于类和类的基本特征(所谓的封装、继承、多态)了解始终不是很到位,同时在理论我的项目利用中也用的比拟少,明天小编就联合ES5中的根本用法和大家聊聊,心愿小伙伴会在这篇文章有属于本人的播种,并可能在今后的我的项目中有理论利用。大家也能够关注我的微信公众号,蜗牛全栈。
一、类的根本用法

function People(name,age){    // this指向的是People{}    this.name = name    this.age = age}let p1 = new People("lilei",30)console.log(p1) // People{name:"lilei",age:34}let p2 = new People("hanmei",18)console.log(p2) // People{name:"hanmei",age:18}

二、类的办法:该实例中会有一些资源节约,因为在每一个实例化的时候,在类中都会存在该办法,理论中为了节约资源,会将类办法定义在原型上

function People(name,age){    // this指向的是People{}    this.name = name    this.age = age    this.showName = function(){        console.log("以后人的名字是:"+this.name)    }}let p1 = new People("lilei",30)console.log(p1) // People{name:"lilei",age:34}p1.showName() // 以后人的名字是:lileilet p2 = new People("hanmei",18)console.log(p2) // People{name:"hanmei",age:18}p2.showName() // 以后人的名字是:hanmei

三、理论类办法创立实例

function People(name,age){    this.name = name    this.age = age}People.prototype.showName = function(){    console.log(this.name)}let p1 = new People("lilei",30)console.log(p1) // People{name:"lilei",age:34}p1.showName() // lileilet p2 = new People("hanmei",18)console.log(p2) // People{name:"hanmei",age:18}p2.showName() // hanmei

四、类的动态属性和静态方法:上述的例如name和age属性,都是实例化之后才有的属性和办法,上述属性和办法个别称为实例属性和实例办法,须要类实例化之后才能够解决的属性,实例办法须要把类实例化之后能力调用。动态属性和静态方法能够通过类间接调用,不用实例化。
类的动态属性

function People(name,age){    // this指向的是People{}    this.name = name // 实例属性    this.age = age // 实例属性}People.count = 10console.log(People.count) // 10

类的静态方法

function People(name,age){    // this指向的是People{}    this.name = name // 实例属性    this.age = age // 实例属性}People.getCount = function(){    console.log("以后数字为"+People.count)}console.log(People.count) // 10

五、类的继承
1、构造函数继承:只能继承父类的属性,不能继承父类的办法

// 父类function Animal(name){    this.name = name}Animal.prototype.showName = function(){    console.log("名字是:"+this.name)}// 子类function Dog(name,color){    Animal.call(this,name) // 继承属性    this.color = color}let d1 = new Dog("wangcai","white")console.log(d1) // Dog{name:"wangcai",color:"white"}d1.showName() // 报错:d1.showName is not a function // 构造函数继承只能继承父类的属性,不能继承父类的办法

2、原型继承:只能继承父类办法,不能继承父类属性

// 父类function Animal(name){    this.name = name}Animal.prototype.showName = function(){    console.log("名字是:"+this.name)}// 子类function Dog(name,color){    // Animal.call(this,name) // 继承属性    this.color = color}Dog.prototype = new Animal()Dog.prototype.constuctor = Doglet d1 = new Dog("wangcai","white")console.log(d1) // Dog{name:"wangcai",color:"white"}d1.showName() // undefind