第一个的内存占用总是会更大。考虑将prototype
作为所有实例可以使用的方法的共享包。这是有效的,因为您不为每个实例创建一个新函数,但是您正在重用已经存在于内存中的现有方法。
好消息是您展示的两种方式可以结合使用。
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() { .. },
// ...
};
};
注意,我故意改变MyClass的小写,因为它不再是一个构造函数并没有必要调用时使用new
!
UPDATE - 有哪些好适合您的需要为第三图案:
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);
},
// ...
};
})();
作为一个说明,你可以使用[用(这个){}(http://javascript.about.com/library/blwith.htm),如果它可以帮助你。 – 2010-11-07 07:02:35
请勿使用“with”。使用这种软件很危险,并且将会从将来的ECAMScript实现中删除。无法强调这一点 - 假设在JavaScript中不存在“with”是好得多。 – Hamish 2010-11-07 07:14:30
如果你这样做,如果你做任何继承,你需要更加小心你做什么,如何混合这两种技术,当你调用超级构造函数等等。 – 2010-11-20 02:01:16