Skip to content Skip to sidebar Skip to footer

How Do I Create A Javascript Object With Defined Variables And Functions?

Let's say I want to create an Object called 'Vertex'. Usually, in Java I would do this by: public class Vertex { // member variables public data; private id; // membe

Solution 1:

http://robertnyman.com/2008/10/14/javascript-how-to-get-private-privileged-public-and-static-members-properties-and-methods/ explains it in excruciating detail. In your case...

// Constructor
function Vertex (data) {
    // Privatevar id = 1;

    // Privilegedthis.getID= function () {
        return id;
    };

    // Publicthis.data = data;
}

// Public
Vertex.prototype.getData = function () {
    returnthis.data;
};

// Static property
Vertex.static = "something";

Solution 2:

There are many, many ways to make a class/instance system similar to what you're using to in other languages, out of JavaScript's curious implementation of prototypes. There's no one single accepted way that everyone uses, and lots of possible trade-offs for convenience and performance. See this question for a discussion of different common class/instance models.

Whilst you can reproduce (mostly-)private variables by using a closure, I would strongly advise against it. You've little to gain by bringing Java's model of privileges to JavaScript.

Java needs private members to be enforced as part of its security model. But JavaScript has no model for in-page security boundaries, so you're not protecting your code against misuse by anyone but yourself. All ‘real privates’ will do for you is make rapid debugging and prototyping work a bit harder.

Consider instead using the honour system model (as in eg Python). Prefix ‘pseudo-private’ members with an underscore to signal that those members should not be accessed from the outside.

Solution 3:

You could use JSDoc to add meta information (like private membership) to your variables and functions. Tools like the Google closure compiler can use this meta information to check your code for illegal access to these members. (and many other things as well)

Post a Comment for "How Do I Create A Javascript Object With Defined Variables And Functions?"