什么是写一个java类,Java什么是类?class的相关介绍
本章給大家?guī)鞪ava什么是類?class的相關(guān)介紹,讓大家了解關(guān)于類(class)的一些知識。有一定的參考價(jià)值,有需要的朋友可以參考一下,希望對你有所幫助。class Point{
constructor(){
}
toString(){
}
}
console.log(Object.keys(Point.prototype))
console.log(Object.getOwnPropertyNames(Point.prototype))
上面就是一個(gè)類
1、類的數(shù)據(jù)類型就是函數(shù),類本身就指向構(gòu)造函數(shù)console.log(typeof Point) // "function"
console.log(Point ===Point.prototype.constructor) // true
2、構(gòu)造函數(shù)的 prototype 屬性在 ES6 的“類”上繼續(xù)存在。事實(shí)上,類的所有方法都定義在類的 prototype 屬性上。
開頭的代碼等同于class Point{}
Point.prototype = {
constructor() {},
toString() {},
}
由于類的方法(除 constructor 以外)都定義在 prototype 對象上,所以類的新方法可以添加在 prototype 對象上。 Object.assign 方法可以一次性的向類添加多個(gè)方法
很重要的一點(diǎn),類的內(nèi)部定義的所有方法都是不可枚舉的。console.log(Object.keys(Point.prototype)) // []
console.log(Object.getOwnPropertyNames(Point.prototype)) // ["constructor", "toString"]
其中,Object.keys() 返回一個(gè)數(shù)組,包含對象自身所有可枚舉屬性,不包含 Symbol,Object.getOwnPropertyNames() 返回一個(gè)數(shù)組,包含自身所有屬性,不包含 Symbol
3、constructor方法
constructor 方法是類的默認(rèn)方法,通過 new 命令生成對象實(shí)例是自動調(diào)用該方法。一個(gè)類必須有 constructor 方法,如果沒有定義,一個(gè)空的 constructor 方法會被默認(rèn)添加。
constructor 方法默認(rèn)返回實(shí)例對象,也就是 this 的指向。不過完全可以指定返回另外一個(gè)對象
4、繼承class ColorPoint extends Point {
constructor(x, y, color) {
super(x, y) // 調(diào)用父類的 constructor(x, y)
this.color = color
}
toString() {
return this.color + '' + super.toString() // 調(diào)用父類的 toString()
}
}
看到 extends 是不是很熟悉,用過 React 的人肯定知道,在 React 的 ES6 寫法中我們經(jīng)常這樣寫class XXXXX extends Component{}
ColorPoint 通過 extends 可以繼承 Point 類的所有屬性和方法
有沒有留意到 constructor 和 toString方法中都出現(xiàn)了 super 關(guān)鍵字,他指代父類的實(shí)例。
子類必須在 constructor 方法中調(diào)用 super 方法,否則新建實(shí)例就會報(bào)錯(cuò)。因?yàn)樽宇悰]有自己的 this 對象,而是繼承了父類的 this 對象,如果不調(diào)用 super ,子類就得不到 this。
其實(shí) class 就是對對象原型的一種更加簡潔的寫法
總結(jié)
以上是生活随笔為你收集整理的什么是写一个java类,Java什么是类?class的相关介绍的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 1亩等于多少平方米?
- 下一篇: 电机37hp等于多少千瓦?