- class 声明的类,类似于 let const 声明的变量一样会进入暂时性死区
var Foo = function () {
this.foo = 21;
};
{
console.log(Foo); // ReferenceError: Cannot access 'Foo' before initialization
class Foo {
constructor() {
this.foo = 37;
}
}
}
function Foo() {
foo = 123
console.log(foo)
}
Foo() // 123
class Bar {
constructor() {
bar = 123
}
}
let bar = new Bar() // ReferenceError: Cannot access 'bar' before initialization
- class 的所有方法 ( 包括静态方法和实例方法 ) 都是不可枚举的
function Foo() {
this.foo = 18
}
Foo.getF1 = function() {
console.log(this.foo)
}
Foo.prototype.getF2 = function() {
console.log(this.foo)
}
console.log(Object.keys(Foo)) // ["getF1"]
console.log(Object.keys(Foo.prototype)) // ["getF2"]
class Bar {
constructor() {
this.bar = 18
}
static getB1() {
console.log(this.bar)
}
getB2() {
console.log(this.bar)
}
}
console.log(Object.keys(Bar)) // []
console.log(Object.keys(Bar.prototype)) // []
- class 的所有方法 ( 包括静态方法和实例方法 ) 都没有原型对象 prototype,所以也没有 [[constructor]],不能使用 new 来调用
function Foo() {
this.foo = 18
}
Foo.getF1 = function() {
console.log(this.foo)
}
Foo.prototype.getF2 = function() {
console.log(this.foo)
}
const foo = new Foo()
console.log(new foo.getF2()) // Foo.getF2 {}
class Bar {
constructor() {
this.bar = 18
}
static getB1() {
console.log(this.bar)
}
getB2() {
console.log(this.bar)
}
}
const bar = new Bar()
console.log(new bar.getB2()) // TypeError: Bar.getB2 is not a constructor
class Bar {
constructor() {
this.bar = 18
}
static getB1() {
console.log(this.bar)
}
getB2() {
console.log(this.bar)
}
}
const bar = new Bar()
Bar() // TypeError: Class constructor Bar cannot be invoked without 'new'
function Bar() {
Bar = 'Baz'; // it's ok
this.bar = 42;
}
const bar = new Bar();
console.log(Bar) // 'Baz'
console.log(bar) // Bar {bar: 42}
class Foo {
constructor() {
this.foo = 42;
Foo = 'Fol'; // TypeError: Assignment to constant variable
}
}
const foo = new Foo();
网友评论