How to “properly” create a custom object in JavaScript?

后端 未结 15 2264
被撕碎了的回忆
被撕碎了的回忆 2020-11-21 08:07

I wonder about what the best way is to create an JavaScript object that has properties and methods.

I have seen examples where the person used var self = this<

15条回答
  •  执笔经年
    2020-11-21 08:29

    I use this pattern fairly frequently - I've found that it gives me a pretty huge amount of flexibility when I need it. In use it's rather similar to Java-style classes.

    var Foo = function()
    {
    
        var privateStaticMethod = function() {};
        var privateStaticVariable = "foo";
    
        var constructor = function Foo(foo, bar)
        {
            var privateMethod = function() {};
            this.publicMethod = function() {};
        };
    
        constructor.publicStaticMethod = function() {};
    
        return constructor;
    }();
    

    This uses an anonymous function that is called upon creation, returning a new constructor function. Because the anonymous function is called only once, you can create private static variables in it (they're inside the closure, visible to the other members of the class). The constructor function is basically a standard Javascript object - you define private attributes inside of it, and public attributes are attached to the this variable.

    Basically, this approach combines the Crockfordian approach with standard Javascript objects to create a more powerful class.

    You can use it just like you would any other Javascript object:

    Foo.publicStaticMethod(); //calling a static method
    var test = new Foo();     //instantiation
    test.publicMethod();      //calling a method
    

提交回复
热议问题