构造函数和class的区别


在es5中构造函数其实就是在定义一个类,可以实例化对象,
es6中class其实是构造函数的语法糖。
但还是有点区别的:

1、预解析

class类不存在预解析,也就是不能先调用class生成实例,再定义class类,但是构造函数可以。

const bar = new Bar(); // it's ok
function Bar() {
    
    
  this.bar = 42;
}

const foo = new Foo(); // ReferenceError: Foo is not defined
class Foo {
    
    
  constructor() {
    
    
    this.foo = 42;
  }
}

2、严格模式

在class内部和class的方法内部,默认使用严格模式,但是构造函数可以不采用严格模式。

// 引用一个未声明的变量
function Bar() {
    
    
  baz = 42; // it's ok
}
const bar = new Bar();

class Foo {
    
    

  constructor() {
    
    
    fol = 42; // ReferenceError: fol is not defined
  }
}
const foo = new Foo();

3、方法(包括静态方法和实例方法)能否被枚举

class中定义的方法(包括静态方法和实例方法)默认不能被枚举,也就是不能被遍历。

// 引用一个未声明的变量
function Bar() {
    
    
  this.bar = 42;
}
Bar.answer = function() {
    
    
  return 42;
};
Bar.prototype.print = function() {
    
    
  console.log(this.bar);
};
const barKeys = Object.keys(Bar); // ['answer']
const barProtoKeys = Object.keys(Bar.prototype); // ['print']

class Foo {
    
    
  constructor() {
    
    
    this.foo = 42;
  }
  static answer() {
    
    
    return 42;
  }
  print() {
    
    
    console.log(this.foo);
  }
}
const fooKeys = Object.keys(Foo); // []
const fooProtoKeys = Object.keys(Foo.prototype); // []

4、是否有prototype

class 的所有方法(包括静态方法和实例方法)都没有原型对象 prototype,不能使用 new 来调用。

function Bar() {
    
    
  this.bar = 42;
}
Bar.prototype.print = function() {
    
    
  console.log(this.bar);
};

const bar = new Bar();
const barPrint = new bar.print(); // it's ok

class Foo {
    
    
  constructor() {
    
    
    this.foo = 42;
  }
  print() {
    
    
    console.log(this.foo);
  }
}
const foo = new Foo();
const fooPrint = new foo.print(); // TypeError: foo.print is not a constructor

5、是否必须使用new执行

class必须使用new执行,但是构造函数没有new也可以执行。

function Bar() {
    
    
  this.bar = 42;
}
const bar = Bar(); // it's ok

class Foo {
    
    
  constructor() {
    
    
    this.foo = 42;
  }
}
const foo = Foo(); // TypeError: Class constructor Foo cannot be invoked without 'new'

6、内部是否可以重写类名

class 内部无法重写类名。

function Bar() {
    
    
  Bar = 'Baz'; // it's ok
  this.bar = 42;
}
const bar = new Bar();
// Bar: 'Baz'
// bar: Bar {bar: 42}  

class Foo {
    
    
  constructor() {
    
    
    this.foo = 42;
    Foo = 'Fol'; // TypeError: Assignment to constant variable
  }
}
const foo = new Foo();
Foo = 'Fol'; // it's ok

7、继承上的差异

  • class中的extends方式的继承,子类.__proto__ === 父类.prototype

  • 构造函数的继承,其子类.__proot__ == Function.prototype

    class中继承可以继承静态方法,但是构造函数的继承不能。

class 继承

class Super {
    
    }
class Sub extends Super {
    
    }

const sub = new Sub();

Sub.__proto__ === Super;

构造函数继承

function Super() {
    
    }
function Sub() {
    
    }

Sub.prototype = new Super();
Sub.prototype.constructor = Sub;

var sub = new Sub();

Sub.__proto__ === Function.prototype;

猜你喜欢

转载自blog.csdn.net/yiyueqinghui/article/details/129361285
今日推荐