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')
    }
    }this

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

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

    }code

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

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

    区别

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



相关文章
相关标签/搜索