es6之前,我們都是通過建構函式來生成例項物件:
function
point
(x,y
)point
.prototype.
sum=
function()
let point =
newpoint(1
,2)console.
log(point.
sum())
// 3
es6 提供了更接近傳統語言的寫法,引入了 class(類)這個概念,基本上,es6 的class可以看作只是乙個語法糖,它的絕大部分功能,es5 都可以做到,新的class寫法只是讓物件原型的寫法更加清晰、更像物件導向程式設計的語法而已。基本語法:
class
point
sum()}
let point =
newpoint(1
,2) console.
log(point.
sum())
// 3
注意:
class
point
tostring()
tovalue()
}// 等同於
point
.prototype =
,tostring()
,tovalue()
,};// object.assign方法可以很方便地一次向類新增多個方法。
object.
assign
(point
.prototype,
,tovalue()
});
class
point
// 等同於
class
point
}
var p1 =
newpoint(2
,3);
var p2 =
newpoint(3
,2);
p1.__proto__ === p2.__proto__
//true
let methodname =
'getarea'
;class
square
[methodname]()
}
const myclass =
classme}
;let inst =
newmyclass()
;inst.
getclassname()
// me
me.name // referenceerror: me is not defined
class
foo}
foo.
classmethod()
// 'hello'
var foo =
newfoo()
;foo.
classmethod()
// typeerror: foo.classmethod is not a function
class
increasingcounter
increment()
}
class
myclass
}
function
person
(name
)else
}
es6之class的繼承 參考文件
前端高階精選:點此去
ES6基本的語法 八 Class
es7 class 的新特性 function point x,y point.prototype.tostring function const p newpoint 1 2 使用 class 之後 class point tostring const p newpoint 1 2 上面的 中定義...
es6隨手記 Class的基本語法
es6中的類 實際上是建構函式的另一種寫法 class aa var b new aa b.dostuff aaa 實際上類上的所有方法也都定義到了這個類的prototype屬性上 上面等同於 aa.prototype 類上定義的方法是不可列舉的,這個和es5中有所區別。所以可以使用下面方法 obj...
es6 基本語法
es6規定暫時性死區和let const語句不出現變數提公升,主要是為了減少執行時錯誤,防止在變數宣告前就使用這個變數,從而導致意料之外的行為。這樣的錯誤在 es5 是很常見的,現在有了這種規定,避免此類錯誤就很容易了。總之,暫時性死區的本質就是,只要一進入當前作用域,所要使用的變數就已經存在了,但...