★ ES5/ES6 的继承除了写法以外还有什么区别

2020-05-29  本文已影响0人  行走的蛋白质
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
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)) // []
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();
上一篇下一篇

猜你喜欢

热点阅读