getter 和 setter 和 defineProperty
- getter:將物件屬性系結到查詢該屬性時將被呼叫的函式
- 說人話就是,當你呼叫一個getter屬性時會呼叫定義好的get函式,這個函式會回傳一些運算結果的值(一般是用其他屬性作為運算值),這個值就作為你呼叫的這個屬性的值,
- setter: 當嘗試設定屬性時,set語法將物件屬性系結到要呼叫的函式
- 說人話就是,當你設定一個setter屬性的值時會呼叫定義好的set函式(可以傳入引數),這個函式會將這個物件的其他屬性設定為傳入的引數計算過后的值,
- 使用defineProperty在現有物件上定義getter:
要隨時將getter添加到現有物件上,使用Object.defineProperty()
const o = { a:0 }
Object.defineProperty(o, 'b', { get: function() {return this.a + 1}});
console.log(o.b) // Runs the getter, which yields a + 1(which is 1)
- 使用defineProperty為當前物件定義setter
const o = { a: 0 }
Object.defineProperty(o, 'b', {set: function(x) { this.a = x/2; }});
o.b = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property
console.log (o.a) // 5
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/262427.html
標籤:其他
上一篇:一個巧合,我把檔案寫進了代碼里
下一篇:一個巧合,我把檔案寫進了代碼里
