JavaScript constructors using JavaScript object literal notation

前端 未结 6 1732
半阙折子戏
半阙折子戏 2021-01-30 15:30

What is the best way to build constructors in JavaScript using object literal notation?

var myObject = {
 funca : function() {
  //...
 },

 funcb : function() {         


        
6条回答
  •  温柔的废话
    2021-01-30 15:35

    Sorry for being late to the party, but... I think saying that this is not possible is a little restrictive depending on how you interpret the OP's question and subsequent comments.

    Assuming the OP wanted the namespacing benefits that object literal notation can bring to a library but also wanted to have some "classes" to use within that structure. Could you not use something of this form to combine constructor patterns in to an object literal notation namespaced library structure?

    var myNamespace = {
        aProperty: "A value",
    
        aMethod: function () { return "A method result"; },
    
        onePlusOneEquals: function () {
            return new myNamespace.classes.NumberStuff(1, 1).added;
        },
    
        classes: {
            ClassA: function () {
                this.propertyOne = null;
                this.methodOne = function (param) {
                    return "The method was passed " + param;
                }
            },
    
            NumberStuff: function (argOne, argTwo) {
                this.added      = argOne + argTwo;
                this.subtracted = argOne - argTwo;
            }
        }
    };
    
    myNamespace.classes.ClassA.prototype.methodTwo = function () { return "At least this one's not bloating our memory footprint with every ClassA created..."; };
    
    ...
    
    var anObj = new myNamespace.classes.ClassA();
    alert(anObj.methodOne("the parcel")); // "The method was passed the parcel"
    alert(myNamespace.onePlusOneEquals()); //2
    

    They're silly examples, but is there any reason not to do this, or why this isn't valid? It gets rid of the global crowding problem that people usually want to use object literal notation for with libraries.

提交回复
热议问题