es6中的类及es5类的实现
生活随笔
收集整理的這篇文章主要介紹了
es6中的类及es5类的实现
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
目錄
- 類的特點
類的特點
1.類只能通過new得到
在es6中類的使用只能是通過new,如果你將它作為一個函數(shù)執(zhí)行,將會報錯。
//es6的寫法 class Child {constructor() {this.name = 1;} } let child = new Child(); console.log(child.name)//1 //如果直接方法調用的形式,會報錯 let child = Child();//Class constructor Child cannot be invoked without 'new'es5中的class其實就是一個方法,沒有關鍵字class
//es5中類的寫法,但是這樣直接用方法名調用并不會報錯 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()//不報錯為了實現(xiàn)類似于es6中的調用檢查,我們需要自己手寫一個調用檢查的函數(shù)。這個函數(shù)的原理就是用當前的this和構造函數(shù)進行比較,如果這個this指向的window,那么可以看出是用通過方法名直接調用的,如果this是構造函數(shù)那么就是通過new得到的
var Person = (function () { //類的調用檢測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()子類會繼承父類的公有屬性和靜態(tài)方法
es6中的寫法
//es6中的寫法 class Child extends Person {constructor() {super()this.name = 1;} } //es5中的寫法 var Clild = (function (Person) { //類的調用檢測function _classCheck(instance, constructor) {if (!(instance instanceof constructor)) {throw new Error('Class constructor Child cannot be invoked without new')}} //子類繼承父類的方法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)//子類繼承私有屬性let that=this;if(typeof obj=='object'){that=obj}that.name=1;//解決了父類是引用類型的問題_classCheck(this, Clild)return that} return Clild; })(Person);轉載于:https://www.cnblogs.com/hanqingtao/p/9957043.html
總結
以上是生活随笔為你收集整理的es6中的类及es5类的实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java开发笔记(二十三)数组工具Arr
- 下一篇: 本周学习总结JAVA