如何使用定义的变量和函数创建JavaScript对象? [英] How do I create a JavaScript Object with defined variables and functions?

查看:47
本文介绍了如何使用定义的变量和函数创建JavaScript对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我要创建一个名为顶点"的对象.通常,在Java中,我可以通过以下方式做到这一点:

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; }
}

现在,我该如何在JavaScript中做到这一点?我想保留私人还是公共?到目前为止,这是我设置的,但我认为这是不对的,而且我从未使用过JavaScript中的OOP.

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);
    }
};

我对原型根本不熟悉,但是我正在尝试学习.这是正确的方法吗?如果不是这样,我基本上是在尝试通过JavaScript来完成上述Java代码的工作.

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.

推荐答案

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";

这篇关于如何使用定义的变量和函数创建JavaScript对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆