es6中的类及es5类的实现
生活随笔
收集整理的這篇文章主要介紹了
es6中的类及es5类的实现
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
目錄
- 類(lèi)的特點(diǎn)
類(lèi)的特點(diǎn)
1.類(lèi)只能通過(guò)new得到
在es6中類(lèi)的使用只能是通過(guò)new,如果你將它作為一個(gè)函數(shù)執(zhí)行,將會(huì)報(bào)錯(cuò)。
//es6的寫(xiě)法 class Child {constructor() {this.name = 1;} } let child = new Child(); console.log(child.name)//1 //如果直接方法調(diào)用的形式,會(huì)報(bào)錯(cuò) let child = Child();//Class constructor Child cannot be invoked without 'new'es5中的class其實(shí)就是一個(gè)方法,沒(méi)有關(guān)鍵字class
//es5中類(lèi)的寫(xiě)法,但是這樣直接用方法名調(diào)用并不會(huì)報(bào)錯(cuò) var Person = (function () {function Person(name) {this.name = name;}Person.prototype.SayHello = function () {window.alert("My name is " + this.name + ".");};return Person; })(); var p = Person()//不報(bào)錯(cuò)為了實(shí)現(xiàn)類(lèi)似于es6中的調(diào)用檢查,我們需要自己手寫(xiě)一個(gè)調(diào)用檢查的函數(shù)。這個(gè)函數(shù)的原理就是用當(dāng)前的this和構(gòu)造函數(shù)進(jìn)行比較,如果這個(gè)this指向的window,那么可以看出是用通過(guò)方法名直接調(diào)用的,如果this是構(gòu)造函數(shù)那么就是通過(guò)new得到的
var Person = (function () { //類(lèi)的調(diào)用檢測(cè)function _classCheck(instance, constructor) {if (!(instance instanceof constructor)) {throw new Error('Class constructor Child cannot be invoked without new')}}function Person(name) {this.name = name;_classCheck(this, Person)}Person.prototype.SayHello = function () {window.alert("My name is " + this.name + ".");};return Person; })(); var p = Person()子類(lèi)會(huì)繼承父類(lèi)的公有屬性和靜態(tài)方法
es6中的寫(xiě)法
//es6中的寫(xiě)法 class Child extends Person {constructor() {super()this.name = 1;} } //es5中的寫(xiě)法 var Clild = (function (Person) { //類(lèi)的調(diào)用檢測(cè)function _classCheck(instance, constructor) {if (!(instance instanceof constructor)) {throw new Error('Class constructor Child cannot be invoked without new')}} //子類(lèi)繼承父類(lèi)的方法function _inherins(subclass, superclass) {subclass.prototype = Object.create(superclass.prototype, { constructor: { value: subclass } })Object.setPrototypeOf(subclass, superclass)}_inherins(Clild, Person)function Clild() {let obj=Person.call(this)//子類(lèi)繼承私有屬性let that=this;if(typeof obj=='object'){that=obj}that.name=1;//解決了父類(lèi)是引用類(lèi)型的問(wèn)題_classCheck(this, Clild)return that} return Clild; })(Person);轉(zhuǎn)載于:https://www.cnblogs.com/hanqingtao/p/9957043.html
總結(jié)
以上是生活随笔為你收集整理的es6中的类及es5类的实现的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Java开发笔记(二十三)数组工具Arr
- 下一篇: 安卓智能机呼叫转移在哪里设置?