2015年4月14日 星期二

底線在javascript代表什麼(_index...等)


 有時會看到像這樣的寫法
var Gallery = Backbone.Controller.extend({
    _index: null,
    _photos: null,
    _album :null,
    _subalbums:null,
    _subphotos:null,
    _data:null,
    _photosview:null,
    _currentsub:null,
    routes: {
        "": "index",
        "subalbum/:id": "subindex",
        "subalbum/:id/" : "directphoto",
        "subalbum/:id/:num" : "hashphoto"
    },
    initialize: function(options) {
        var ws = this;
        if (this._index === null){
            $.ajax({
                url: 'data/album1.json',
                dataType: 'json',
                data: {},
                success: function(data) {
                    ws._data = data;
                    ws._photos =
                    new PhotoCollection(data);
                    ws._index =
                    new IndexView({model: ws._photos});
                    Backbone.history.loadUrl();
                }
            });
            return this;
        }
        return this;
    },
    //Handle rendering the initial view for the
    //application
    index: function() {
        this._index.render();
    },
 裡面的_index為何前面要有個底線呢?

答:
這代表他是私用方法(private methods),只給內部使用,無法在外部類別裡被使用
通常這樣寫並非是說要這樣寫才能被當私用方法或才能被執行,比較像是做個註記讓人知道它是私用方法。

心得:
這似乎是OOP裡的一個概念,下方有個人回說
at least, the idea of private fields is there, but they aren't really private, you can access them anyway. the author of the above code just meant for them to be private. that's all. –  Sander Nov 27 '11 at 23:29


意思是其實對JS來說沒有真正所謂的私用方法?

http://stackoverflow.com/questions/8288756/in-javascript-what-does-this-underscore-mean