2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

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

what the best way is to create an object that has properties and methods.

Few examples show  "var self = this" and then uses "self." in all functions to make sure the scope is always correct.Then I have seen examples of using .prototype to add properties, while others do it inline. Please mention a proper example of a JavaScript object with some Properties and Methods?

userimage

I research found some way which gives me a pretty huge amount of flexibility when I need it. In use it's rather similar to Java-style classes.

var myFunction = function()

{

    var privateStaticMethod = function() {};

    var privateStaticVariable = "someVariable";

    var constructor = function myFunction(someVariable, bar)

    {

        var privateMethod = function() {};

        this.publicMethod = function() {};

    };

    constructor.publicStaticMethod = function() {};

    return constructor;

}();

This snippet 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 also 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

Answer is