简体   繁体   English

访问JavaScript对象中的方法

[英]accessing methods in JavaScript object

Consider the following Java script code: 考虑以下Java脚本代码:

    var myObj = function (  ) {
        var x = 0;
        return {
            addup: function (y) {
                x += y;
            },
            getX: function (  ) {
                return x;
            }
        }
    }();

This function returns an object with two methods (if I am not wrong). 此函数使用两种方法返回对象(如果我没记错的话)。

now, two questions: 现在,有两个问题:

  1. how can I call the two methods returned from the function? 如何调用函数返回的两个方法?
  2. can those methods still have access to the variable x ? 这些方法仍然可以访问变量x吗?

thanks, 谢谢,

  1. myObj.getX(); and myObj.addup(5); myObj.addup(5);
  2. Yes, they still have access 是的,他们仍然可以访问

Example - http://jsfiddle.net/qWT9N/ 示例-http://jsfiddle.net/qWT9N/

how can I call the two methods returned from the function? 如何调用函数返回的两个方法?

myObj.addup(10);
var xValue = myObj.getX();

can those methods still have access to the variable x ? 这些方法仍然可以访问变量x吗? Yes

You've created "template" object myObj with private x propery and two public methods. 您已经使用私有x属性和两个公共方法创建了“模板”对象myObj

To create object based on your "template" call var obj = myObj(); 要基于“模板”创建对象,请调用var obj = myObj();

  1. You can call them like obj.addup(2); 您可以像obj.addup(2);那样称呼它们obj.addup(2); and obj.getX(); obj.getX();
  2. Yes those methods have access to Private x variable from them 是的,那些方法可以从中访问Private x变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM