我是Python背景的人,我看過這個,學習Javascript:
類實際上是 "特殊的函式",正如你可以定義函式運算式和函式宣告一樣,類的語法有兩個組成部分:類運算式和類宣告。
在dev.mozilla網站...
我所理解的是:
函式是OOP中的物件
而不是類是函式。
也許類本身也是物件。我不確定。
我錯了嗎?
我錯了嗎?
uj5u.com熱心網友回復:
類的確是函式,而且函式也是物件--你可以把任意的鍵值對放到函式上,就像放到物件上一樣。
。class X{}。
console.log(typeof X)。
console.log(X instanceof Object);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
這就是一個類宣告。一個類的運算式是這樣的:
。const TheX = class X{}。
console.log(typeof TheX) 。
console.log(TheX instanceof Object);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
。
class X{
static prop = 'foo';
}
console.log(X.hasOwnProperty);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
用class創建的類不能在沒有new的情況下被呼叫,但是用function創建的類可以(在這種情況下,它相當于一個標準函式)。
function X() {
}
//作為一個類:
const x = new X() 。
//作為一個普通的函式:
const somethingElse = X();
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
在function語法中,函式是作為一個類還是作為一個普通的函式,是由呼叫者決定的--通過是否使用new。如果使用了new,函式中的this將被設定為一個繼承自X.prototype的物件,它將在最后自動回傳。如果沒有使用new,函式中的this將被設定為呼叫的背景關系,如果有的話(例如someObj.X()將使this成為someObj)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/313407.html
標籤:
上一篇:實作所需類層次行為的最佳方式
