1普通创建类的方法

  1. function Modal(x, y) {
  2. // 给实例设置的私有属性方法
  3. this.x = x;
  4. this.y = y;
  5. }
  6. // 在类的原型上扩展的公共属性方法「供实例调用的」
  7. Modal.prototype.z = 10;
  8. Modal.prototype.getX = function () {
  9. console.log(this.x);
  10. }
  11. Modal.prototype.getY = function () {
  12. console.log(this.y);
  13. }
  14. // 把它当做普通对象,设置的静态私有属性方法
  15. Modal.n = 200;
  16. Modal.setNumber = function (n) {
  17. this.n = n;
  18. };

2.用ES6语法

class创建的构造函数,不能Fn()执行,只能new执行 不能给原型增加属性,只能增加方法

  1. class Model {
  2. // 构造函数体:给实例设置的私有属性和方法
  3. constructor(x, y) {
  4. this.x = x;
  5. this.y = y;
  6. }
  7. // z = 10; //直接这样写,是给实例设置的私有属性
  8. // 向类的prototype上扩展方法{特点:这里只能给prototype设置公共的方法,属性设置不了,如果想设置,只能在外面自己加}
  9. getX() {
  10. console.log(this.x);
  11. }
  12. getY() {
  13. console.log(this.y);
  14. }
  15. // 当做普通对象,设置的静态私有属性方法
  16. static n = 20;
  17. static setNumber(n) {
  18. this.n = n;
  19. }
  20. }
  21. Model.prototype.z = 10;
  22. let m = new Model(10, 20);
  23. //Model() //Uncaught TypeError: Class constructor Model cannot be invoked without 'new'

例2:

  1. // function Fn(num) {
  2. // this.x = this.y = num;
  3. // }
  4. // Fn.prototype.x = 20;
  5. // Fn.prototype.sum = function () {
  6. // console.log(this.x + this.y);
  7. // };
  8. // Fn.a = 1;
  9. class Fn {
  10. constructor(num) {
  11. this.x = this.y = num;
  12. }
  13. // x=20;不能直接在class里面增加原型上的属性,实例私有的
  14. a=1;//实例私有的
  15. static b=2;//写在函数堆里Fn的私有属性
  16. sum() {
  17. // Fn原型上的
  18. console.log(this.x + this.y);
  19. }
  20. }
  21. Fn.prototype.a=1;//原型上的属性a
  22. // class创建的构造函数不能Fn(),只能new Fn。
  23. console.dir(new Fn);

image.png
image.png