對象 get和set方法


1、用途

用戶定義的對象定義 getter 和 setter 以支持新增的屬性。

示例:obj創建一個偽屬性latest,它會返回log數組的最后一個元素。

var obj = { log: ['example','test'], get latest() { if (this.log.length == 0) return undefined; return this.log[this.log.length - 1]; } } console.log(obj.latest); // "test".

2、使用defineProperty在現有對象上定義 getter

var 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

3、實用技巧

使用getter和setter方法擴展 Date原型,為預定義好的Date類添加一個year的屬性。定義屬性year的getter和setter方法用到了Date類中已存在的getFullYear和setFullYear方法。

Object.defineProperty(Date.prototype, "year", { get: function() { return this.getFullYear() }, set: function(y) { this.setFullYear(y) } }); var now = new Date(); console.log(now.year); // 2018
            now.year = 2001; console.log(now); //Tue Sep 11 2001 15:10:43 GMT+0800 (中國標准時間)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM