在javascript中选择OOP模式

Rad*_*adu 8 javascript oop model-view-controller design-patterns

我把它们放在其他人和几个资源的帮助下.我已经把所有东西都搞砸了,下面的代码贴在下面.

基本上我已经学会了如何使用这些模式,但我很好奇这些方法之间的根本区别.下游代码实际上与这些模式中的任何一个相同,但是有一个原因是为什么人们应该使用一个而不是个人偏好?虽然我试图收集最常见的模式,但如果它更好,请建议你自己的模式.

模式1(基于对象):

var mouseDiff = {
    "startPoint" : {"x" :0, "y" : 0},
    "hypotenuse" : function(a,b) {
        // do something
    },
    "init"       : function(){
        // do something
    }
}

mouseDiff.init();
Run Code Online (Sandbox Code Playgroud)

模式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();
Run Code Online (Sandbox Code Playgroud)

模式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();
Run Code Online (Sandbox Code Playgroud)

Bre*_*mir 11

模式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();
Run Code Online (Sandbox Code Playgroud)