ES5ES6的继承的区别

7次阅读

共计 1010 个字符,预计需要花费 3 分钟才能阅读完成。

class声明会提升,但是不会被初始化赋值,所以优先初始化赋值,则会进入 暂时性死区 ,类似letconst 变量

const bar = new Bar(); // ok
function Bar() {this.bar = 42;}
const foo = new Foo() // Foo is not defined
class Foo{constructor() {this.foo = 42;}
}

class内部启动 严格模式

function Bar(){baz = 42; // OK}
const bar = new Bar();

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

class的所有方法(包括静态方法和示例方法)都没有原型对象 portotype,所以也没有 [[construct]],不能使用new 来调用

function Bar() {this.bar = 42;}

Bar.prototype.print = function (){console.log(this.bar)
}
const bar = new Bar();
cont barPrint = new bar.print() ; // 42
class Foo {constructor() {this.foo = 42;}
    print () {console.log(this.foo)
    }
}

const foo = new Foo();
const fooPrint = new foo.print(); // foo.print is not a constructor

必须使用 new 来调用class

function Bar() {this.bar = 42;}

const bar = Bar() ; // bar.bar: 42

class Foo() {constructor () {this.foo = 42;}
}

const foo = Foo() // Class constructor Foo cannot be invoked widhout 'new'

class内部无法重写类名

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

class Foo{constructor() {
        this.foo = 12;
        Foo = 'Fol' ; // err:Assignment to constant variable
    }
}

const foo = new Foo();
Foo = 'Fol'; // 

正文完
 0