1
0

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 3 years have passed since last update.

Javascript クラスの書き方

Last updated at Posted at 2020-07-01

Update: 進化版をこちら:

https://qiita.com/koryo/items/06a5959684372dca4c6f

Javascript クラスの書き方。

var Foo = (function(name) {
    var privates = new WeakMap();
 
    function Foo(name) {
        privates.set(this, {});
 
        privates.get(this).prop = 1;
        privates.get(this).name = name;
    }
    Foo.prototype._share = 'share';
    Foo.prototype.changeShare = function(newValue) { Foo.prototype._share = newValue; };
    Foo.prototype.method = function() { return privates.get(this).prop; };
    Foo.prototype.say = function() { console.log(privates.get(this).name); };
 
    return Foo;
})();

var foo1 = new Foo('aaa');
var foo2 = new Foo('bbb');
foo1.say(); // aaa
foo2.say(); // bbb
console.log(foo1.name); // undefined
console.log(foo1.say === foo2.say); // true
console.log(foo1._share === foo2._share); // true
console.log(foo1._share); // share
console.log(foo2._share); // share

/*foo1.share = 'change';*/
foo1.changeShare('change!');
console.log(foo1._share); // change!
console.log(foo2._share); // change!

console.log(foo1.hasOwnProperty("_share")); // false
console.log(foo2.hasOwnProperty("_share")); // false
  1. private 変数ができる。
  2. 共通の変数ができる。(_share)
  3. 外から無理プチこんだら終わりだが、js はそんなもんなので、どうしようもない。

参考元:https://webkatu.com/archives/private-property/

以上。

1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?