<
!doctype html>
"en"
>
"utf-8"
>
"viewport" content=
"width=device-width, initial-scale=1.0"
>
類<
/title>
<
/head>
// 類的宣告
function
animal()
// es6中的class宣告
class
animal2
}// 例項化
console.
log(
newanimal()
,new
animal2()
)// 借助建構函式來實現繼承
function
parent1()
function
child1()
console.
log(
newchild1()
)// 缺點是並沒有真正實現繼承,無法用到原型鏈,只能使用建構函式中的方法來部分繼承
// 借助原型鏈實現繼承
function
parent2()
function
child2()
p =newparent2()
child2.prototype = p
p.constructor = child2
c1 =
newchild2()
c2 =
newchild2()
console.
log(c1.play, c2.play)
c1.play.
push(3
) console.
log(c1.play, c2.play)
// 缺點是引用同乙個原型鏈物件,其原型鏈物件一旦改變,所有例項都會受到影響。
// 組合繼承
function
parent3()
function
child3()
p1 =
newparent3()
//此處可優化
child3.prototype = p1 //直接使child3.prototype = parent3.prototype
p1.constructor = child3//如果不設定這一步,p1沒有constructor屬性,會去原型鏈上拿到parent3.prototype的constructor,也就是parent3
c4 =
newchild3()
c3 =
newchild3()
console.
log(c3.play, c4.play)
c3.play.
push(3
) console.
log(c3.play, c4.play)
// 缺點是new乙個例項,parent3函式執行了兩次
// 組合繼承優化
function
parent4()
function
child4()
child4.prototype = object.
create
(parent4.prototype)
child4.prototype.constructor = child4
c5 =
newchild4()
console.
log(c5.constructor)
<
/script>
<
/body>
<
/html>
c 基礎 類宣告與繼承中的訪問總結
當類宣告的時候,自身的字段,方法無論是私有的,還是公開的,又或者是靜態的,類自身都可以直接用 無需new class test public voidcc static voidtt public static voidyy voidbb 也就是說許可權僅僅是對於其他類,這個其他類即包括沒有任何關係...
類的宣告與定義
什麼是類的宣告與定義?一 變數的宣告與定義很容易區分。宣告只是告訴編譯器有這麼乙個變數,但是沒有為它分配空間 定義則是為該變數分配空間。所以變數可以重複宣告,但是不能重複定義。那麼,類的宣告與定義又是什麼呢?之前以為類的宣告就是為類開闢一塊空間 類的定義就是定義乙個物件,也就是為物件分配空間。實際上...
類的宣告與定義
可以宣告乙個類而不定義它。class screen 宣告而未定義 在宣告之後 定義之前,類screen是乙個不完全型別,即已知screen是乙個型別,但不知道包含哪些成員。不完全型別只能以有限的方式使用。不能用來定義該型別的物件,只能用於定義指向該型別的指標及引用,或用於宣告 不能是定義 使用該型別...