最初のメモリ使用量は常に大きくなります。prototype
すべてのインスタンスが使用できるメソッドの共有パッケージと見なします。インスタンスごとに新しい関数を作成するのではなく、既にメモリ内にある既存のメソッドを再利用しているので効果的です。
良いニュースは、あなたが示した 2 つの方法を組み合わせることができるということです。
MyClass = function () {
var x;
// public method with access
// to private variables
this.sayX = function () {
alert(x);
};
}
// method that doesn't need access to private variables
MyClass.prototype.sharedMethod = function () {
// ...
}
しかし、小さなコードベースを扱っている限り、メモリの使用について心配する必要はありません。次のようなパターンを使用することもできます
// everything will be created for every
// instance, but the whole thing is nicely
// wrapped into one 'factory' function
myClass = function () {
// private variables
var x;
// private methods
function doSomethingWithX() {}
// public interface
return {
sayX: function () {
alert(x);
},
publicMethod: function () { .. },
// ...
};
};
new
myClass はコンストラクター関数ではなく、呼び出し時に使用する必要がないため、意図的に小文字に変更したことに注意してください。
更新- ニーズに適した 3 番目のパターンがあります。
MyClass = function (x, y, whatever) {
this._init.apply(this, arguments);
}
// The prototype creates a scope for data hiding.
// It also includes a constructor function.
MyClass.prototype = (function () {
var x; // private
return {
_init: function (x_in) {
x = x_in;
},
sayX: function () {
alert(x);
},
// ...
};
})();