我在其他人的帮助和一些资源的帮助下将这些放在一起。我做了一个一切的小提琴,下面发布了精简的代码。
基本上我已经学会了如何使用这些模式,但我很好奇这些方法之间更根本的区别。下游代码实际上与这些模式中的任何一种都相同,但是除了个人偏好之外,是否有理由使用其中一种而不是另一种?另外,尽管我尝试收集最常见的模式,但如果更好的话,请提出您自己的模式。
模式 1(基于对象):
var mouseDiff = {
"startPoint" : {"x" :0, "y" : 0},
"hypotenuse" : function(a,b) {
// do something
},
"init" : function(){
// do something
}
}
mouseDiff.init();
模式2(据我所知最传统):
function MouseDiff() {
this.startPoint = {"x" :0, "y" : 0};
}
MouseDiff.prototype.hypotenuse = function(a,b) {
// do something
}
MouseDiff.prototype.init = function() {
// do something
}
var myMouse = new MouseDiff;
myMouse.init();
模式 3(利用闭包):
var MouseDiff2 = (function() {
var startPoint = {"x" :0, "y" : 0};
var hypotenuse = function(a,b) {
// do something
};
return {
hypotenuse: hypotenuse,
init : function(){
// do something
}
};
}());
MouseDiff2.init();
模式 1 是单例模式。如果您只需要一个这样的对象,那就没问题了。
模式 2 构建新对象,并利用prototype
对象,以便当一个新的MouseDiff
创建对象后,它不会创建函数的新副本(它们本身就是 JavaScript 中的数据)。
与常规单例相比,模式 3 需要更多内存,但它提供静态隐私。
我喜欢下面的模式,因为它涵盖了各种功能,尽管它实际上是构造函数(模式 2)和闭包(模式 3)的组合:
var MouseDiff = (function () {
var aStaticVariable = 'Woohoo!';
// And if you really need 100% truly private instance
// variables which are not methods and which can be
// shared between methods (and don't mind the rather
// big hassle they require), see
// http://brettz9.blogspot.com/search?q=relator
// (see also the new plans for a Map/WeakMap in ECMAScript)
function _APrivateStaticMethod () {
alert(aStaticVariable);
}
// An instance method meant to be called on the
// particular object as via ".call(this)" below
function _APrivateInstanceMethod () {
alert(this.startPoint.x);
}
// Begin Constructor
function MouseDiff() {
this.startPoint = {"x" :0, "y" : 0};
}
MouseDiff.prototype.hypotenuse = function(a,b) {
// do something
};
MouseDiff.prototype.init = function() {
// do something
_APrivateStaticMethod(); // alerts 'Woohoo!'
_APrivateInstanceMethod.call(this); // alerts 0 (but if not
// called with this, _APrivateInstanceMethod's internal
// "this" will refer (potentially dangerously) to the
// global object, as in the window in the browser unless
// this class was defined within 'strict' mode in which
// case "this" would be undefined)
};
return MouseDiff;
}());
var myMouse = new MouseDiff;
myMouse.init();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)