es6中類的理解

2021-10-09 06:30:14 字數 2239 閱讀 8480

類的資料型別就是函式,類本身就指向建構函式:

point === point.prototype.constructor

類的所有方法都定義在類的prototype屬性上面。 在類的例項上面呼叫方法,其實就是呼叫原型上的方法

class point 

tostring()

tovalue()

}// 等同於

point.prototype = ,

tostring() {},

tovalue() {},

};

類的內部所有定義的方法,都是不可列舉的:

class point 

tostring()

}object.keys(point.prototype)

// object.getownpropertynames(point.prototype)

類的所有例項共享乙個原型物件

var p1 = new point(2,3);

var p2 = new point(3,2);

p1.__proto__ === p2.__proto__===point.prototype

在「類」的內部可以使用getset關鍵字,對某個屬性設定存值函式和取值函式,攔截該屬性的訪問行為:

class myclass 

get prop()

set prop(value)

}let inst = new myclass();

inst.prop = 123;

// setter: 123

inst.prop

// 'getter'

採用 class 表示式,可以寫出立即執行的 class

let person = new class 

sayname()

}('張三');

person.sayname(); // "張三"

7.靜態方法:加上static關鍵字,就表示該方法不會被例項繼承,直接通過類來呼叫;靜態方法包含this關鍵字,這個this指的是類,而不是例項

class foo 

}foo.classmethod() // 'hello'

靜態屬性: 

//有乙個提案提供了類的靜態屬性

// 老寫法

class foo

foo.prop = 1;

// 新寫法

class foo

8.類的方法內部如果含有this,它預設指向類的例項,單獨使用該方法,很可能報錯

class logger `);

} print(text)

}const logger = new logger();

const = logger;

printname(); // typeerror: cannot read property 'print' of undefined

在構造方法中繫結this,這樣就不會找不到print方法了

class logger 

}

9.例項屬性的新寫法:例項屬性除了定義在constructor()方法裡面的this上面,也可以定義在類的最頂層。

class foo 

}

10.私有屬性和私有方法:

目前,有乙個提案,為class加了私有屬性。方法是在屬性名之前,使用#表示

class increasingcounter 

class foo

#sum()

}

const counter = new increasingcounter();

counter.#count // 報錯

counter.#count = 42 // 報錯

ES6中類的this問題

類裡面的共有屬性和方法一定要加this使用 const x 1class test foo foo const test newtest test.foo 2 test.foo 1 不用this繫結到類時,會直接尋找全域性的變數和方法 test.x 3test.foo 3class的this指向 類...

深入理解ES6之《ES6中較小的改動》

console.log number.isinteger 25 true console.log number.isinteger 25.0 true console.log number.isinteger 25.1 falseieee 754只能準確的表示 2的53次方到2的53次方的整數 le...

理解ES6中class語法

function point result point.prototype.add function var num new point add 建立例項並呼叫add方法 console.log num 列印這個方法的返回值1.宣告類 class point add let num new poin...