2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CoffeeScriptでプロパティをどうしても隠したい時

Last updated at Posted at 2013-01-17

JS同様、closureを使うのです。

fuga.coffee
_ivar = null #this is an ivar

module.exports = class Fuga
  constructor: -> _ivar = 'initated'
  ivar: -> _ivar
  setIvar: (x) -> _ivar = x

使ってみると、

Fuga = require './fuga'

fuga = new Fuga()
console.log fuga.ivar()
# initiated
fuga.setIvar 'changed'
console.log fuga.ivar()
# changed
console.log fuga._ivar
# undefined

_ivarに直接アクセス出来ませんね。

Object.definePropertyと一緒に使うと面白いと思います。

結果的にはこういう風にコンパイルされます。

fuga.js
// Generated by CoffeeScript 1.4.0
(function() {
  var Fuga, _ivar;

  _ivar = null;

  module.exports = Fuga = (function() {

    function Fuga() {
      _ivar = 'initated';
    }

    Fuga.prototype.ivar = function() {
      return _ivar;
    };

    Fuga.prototype.setIvar = function(x) {
      return _ivar = x;
    };

    return Fuga;

  })();

}).call(this);

訂正:以下のコードでは継承時に不具合が起こります。
kaminaly、ありがとうございました。

Crockford法

class Fuga
  constructor: ->
    _ivar = 'initated'
    @ivar = -> _ivar
    @setIvar = (x) -> _ivar = x
2
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?