How to define a class?

What is a class? =="" function, this is a class.

one,

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

}

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

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

Second, let's look at the second method

   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,)

3. ES6 defines a class through 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'

 

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324144663&siteId=291194637