對象
JavaScript中所有的事物都是對象:字符串己肮、數(shù)值耿眉、數(shù)組、函數(shù)等等耸黑。此外玷室,JavaScript還允許自定義對象零蓉。
對象只是一種特殊的數(shù)據(jù),對象擁有屬性和方法穷缤。
類
在ES6中敌蜂,class(類)作為對象的模板被引入,可以通過class關(guān)鍵字定義類津肛。class的本質(zhì)是一個(gè)function章喉,它可以看作是一個(gè)語法糖,讓對象原型的寫法更加i清晰身坐、更像面向?qū)ο缶幊痰恼Z法秸脱。
1. 類定義
// 匿名類
let Example1 = class {
constructor(a) {
this.a = a
}
}
// 命名類
let Example2 = class Example {
constructor(a) {
this.a = a
}
}
2. 類聲明
class Example {
constructor(a) {
this.a = a
}
}
類不可重復(fù)聲明:
class Example{}
class Example{}
// Uncaught SyntaxError: Identifier 'Example' has already been declared
let Example1 = class{}
class Example{}
// Uncaught SyntaxError: Identifier 'Example' has already been declared
且類定義不會(huì)像變量定義一樣將聲明部分提升,這一位置必須在訪問前對類進(jìn)行定義部蛇,否則就會(huì)報(bào)錯(cuò)摊唇。
new Example()
let Example = class {}
// Uncaught ReferenceError: Cannot access 'Example' before initialization
類中方法不需要function關(guān)鍵字,方法見不能加分號涯鲁。