/ walking bear:D / Javascript getter in object literal

Javascript getter in object literal

2017-05-08 posted in [筆記]

看到一段程式碼,使用了 getter 的語法:

var config = {
    debug: true,
    get dosomething() { return !this.debug; },
	// ...
}

查找到這篇文章:MDN getter 提出了兩種語法:

Syntax

{get prop() { ... } }
{get [expression]() { ... } }

Parameters

prop

The name of the property to bind to the given function. ### expression
Starting with ECMAScript 2015, you can also use expressions for a computed property name to bind to the given function. 

寫了一段測試程式來驗證語法:

var expr = function(i) {
        var l = ['True', 'Good'];
        return function() {
                return l[i++ % 2];
        }
}(0);
var obj = {
        list: ['Trueman', 'is', 'a', 'Goodman'],
        get latest() {
                return (this.list.length == 0) ?
                        undefined : this.list[this.list.length - 1];
        },
        get [expr() + 'man']() { return this.list.indexOf('Trueman'); }
};
console.log(obj.latest);              // print "Goodman"
console.log(expr());                   // print "Good"
console.log(obj.Trueman);       // print 0
console.log(obj.Goodman);     // print undefined

發現 expression 的用法會偷偷先呼叫 expr 一次,讓內部的 counter + 1,所以第二行得到 Good,第四行則是 undefined,等於是定義了 Trueman 這個 getter。

MDN 文章末提供了一個用例,或許有機會用到,也記在這裡:

get notifier() {
  delete this.notifier;  // 呼叫後,刪除掉此 getter
  // 再定義相同 property name 的變數值
  return this.notifier = document.getElementById('bookmarked-notification-anchor');
},

. reply_count: 0 get_replies : 0 .

walking bear:DRSS feed

关于

wkliang

Clarke's Three Laws:

  • When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong.
  • The only way of discovering the limits of the possible is to venture a little way past them into the impossible.
  • Any sufficiently advanced technology is indistinguishable from magic.
  • 版权申明

    知识共享许可协议

    Fork me on GitHub

    Powered by

    Disqus, GitHub, Google Custom Search, Gravatar, HighlightJS, jekyll