什么是类?==》》function,这就是一个类。

一、

function person(name,age){
   this.name=name;
   this.age=age;

}

var person1=new person('john',20)  //创建了一个类的实例
console.log(person1)

//这就是定义了一个类,并且创建了一个实例

二、下面我们来看第二种方法

   var person ={
       name:'john',
       age:20,
       hobby:['swimming','basketball','football'],
       do:function(){
           console.log('do sth.')
       }
   }

   var person1=Object.create(person)      //通过Object.create()
   console.log(person1.name,person1.age,person1.hobby,person1.do,)

三、ES6通过class来定义一个类

    let methodName='eat';//定义一个属性的变量
    class Person{
        //constructor内部定义的是实例的方法和属性,外部则是属于Person原型上的
        constructor(name,age){
            this.name=name;
            this.age=age
        }
        do(){
            console.log('play')
        }
        [methodName]='apple' //属性表达式
        static hobby='ball'
    }

    var john=new Person('john',20)
    console.log(john.hasOwnProperty('name'))  //true 实例上的属性
    console.log(john.hasOwnProperty('do'))    //false原型上的属性
    console.log(Person.prototype.hasOwnProperty('do'))  //true //原型上的属性
    console.log(john.hobby)  //undefined  静态属性属于类,实例上是吗没有的

    

    // 继承 extends
    //父类的静态方法,可以被子类继承
    class Person{
        constructor(name){
          this.name=name
        }
        static getAge(){
            return 'myName'
        }
    }

   class john extends Person{}

   console.log(john.getAge())  //myName
    //可以不写constructor和this关键字。 这样比较清晰的找到实例的属性
    class Person{
        hobby='ball';
        name='john'
        play(){
            return `play${this.hobby}`
        }
    }

var john=new Person()
console.log(john)  //hobby='ball'  name='john'
04-26 19:05
查看更多