Class和构造函数的异同

以下两种方式实现相同的功能

  1. 在普通对象上面加两个属性和一个方法

  2. 在原型对象上加一个方法

  3. 在构造函数对象上面加一个方法

    class Student {
    constructor(name, age) {
    this.name = name ;
    this.age = age;
    this.sayName = this.sayName
    },
    sayName() {
    console.log(this.name)
    },
    static sayHello() {
    console.log('helloworld')
    }
    }

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

     this.sayName = function() {
       console.log(this.name)
     }
    

    }

    Student.prototype.sayName = function() {
    console.log(this.name)
    }

    Student.sayHello = function() {
    console.log('helloworld')
    }

区别

  1. 类的形式
    • 可以在Class内部同时定义普通对象的属性方法,定义构造函数对象上面的方法,定义原型对象上面的方法属性
    • 值得注意的是通过静态关键字只能在构造函数对象上面添加方法,也就是说只能定义静态的方法,不能定义静态的属性
  2. 构造函数的形式
    • 在构造函数内部只能定义普通对象上面的方法和属性
    • 静态方法也就是构造函数对象上面的方法,只能通过显式的追加
    • 原型对象上面的方法和属性也需要显式的追加



posted @ 2017-06-14 11:27  飘零的日子  阅读(1397)  评论(0编辑  收藏  举报