es5,es6中的类

/*
        * 程序中类
        * ES6
        * 面向对象: 类
        *          属性
        *          方法
        * 函数模拟
        *
        * 人:Person
        *       属性:name
        *       展示名字:showName
        *
        *
        * */

        //ES5 ES6之前

        function Person(name,age) {
            this.name = name;
            this.age = age;
        }
        //原型写法
      /*  Person.prototype.showName = function () {
            return `名字为${this.name}`
        };
        Person.prototype.showAge = function () {
            return `年龄为:${this.age}`
        };*/

      //Object.assign方法,把方法写进Object里面
        Object.assign(Person.prototype,{
           showName(){
               return `名字:${this.name}`
           } ,
            showAge(){
               return `年龄:${this.age}`
            }
        });
class Person{
        constructor(name,age){//构造函数在对象实列化(调用new的时候)的时候执行
           // console.log(`ES6的构造函数:${name},${age}`)
            //属性在构造函数中
            this.name = name;
            this.age = age;
        }
        //在对象内部直接定义方法,不用挂在对象的prototype上
        showName(){
            return `ES6名字:${this.name}`;
        }
        showAge(){
            return `ES6年龄:${this.age}`;
        }
    }

    let person = new Person("marin",18);
    console.log(person.showName());
    console.log(person.showAge());

猜你喜欢

转载自blog.csdn.net/memedadexixaofeifei/article/details/85915471
今日推荐