How do I create a JavaScript Object with defined v

2019-03-04 13:07发布

问题:

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;

   // member methods
   public Vertex() { /* default constructor */ }
   public getID() { return id; }
}

Now, how would I do that in JavaScript? I want to preserve private vs. public? This is what I have set up so far, but I don't think it is right, and I've never dealt with OOP in JavaScript.

/**
 * Vertex constructor.
 */
function Vertex(object) {

    data = object;
    id = object.getCode(); // each Vertex will have a unique id which will be the city code
};
Vertex.prototype = (function() {
  // Private Members here

  // Public Members inside return
  return {
    constructor : Vertex,

    getID : function() {

        return (id);
    }
};

I'm not familiar at all with prototypes, but I'm trying to learn. Is this the right way to do this? If it isn't, I'm basically trying to accomplish what the above Java code does, but by doing it in JavaScript.

回答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) {
    // Private
    var id = 1;

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

    // Public
    this.data = data;
}

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

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


回答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.



回答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)