Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/403.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
获取并设置javascript函数中的局部变量_Javascript_Variables_Getter Setter_Local Variables - Fatal编程技术网

获取并设置javascript函数中的局部变量

获取并设置javascript函数中的局部变量,javascript,variables,getter-setter,local-variables,Javascript,Variables,Getter Setter,Local Variables,我已经编写了一个代码来获取和设置javascript函数中的局部变量;它不起作用了 function wrapper() { var x = 10; this.getX = function () { return x; //Return x } this.setX = function (newX) { x = newX; //Set value for x } } var obj = wrapper(); obj.g

我已经编写了一个代码来获取和设置javascript函数中的局部变量;它不起作用了

function wrapper() {
    var x = 10;
    this.getX = function () {
        return x; //Return x
    }
    this.setX = function (newX) {
        x = newX; //Set value for x
    }
}

var obj = wrapper();

obj.getX(); //Get value of x in wrapper
obj.setX(25); //Set value of x in wrapper

如何从外部代码获取和设置javascript函数中的局部变量。

作为构造函数调用
包装器

var obj = new wrapper();
…因此,
是“包装器的实例”,而不是“默认对象,
窗口

约定要求构造函数以大写字母命名,因此在整个程序中所有函数都将
wrapper
更改为
wrapper


如需进一步阅读,请参阅。

调用
包装器作为构造函数

var obj = new wrapper();
…因此,
是“包装器的实例”,而不是“默认对象,
窗口

约定要求构造函数以大写字母命名,因此在整个程序中所有函数都将
wrapper
更改为
wrapper

如需进一步阅读,请参阅

或者更好:

function wrapper(){
    this.x = 0;
    this.getX = function(){ return this.x;};
    this.setX = function(x){this.x=x;};
}

var obj = new wrapper();

obj.getX(); //Get value of x in wrapper
obj.setX(25); //Set value of x in wrapper
alert(obj.getX());
或者更好:

function wrapper(){
    this.x = 0;
    this.getX = function(){ return this.x;};
    this.setX = function(x){this.x=x;};
}

var obj = new wrapper();

obj.getX(); //Get value of x in wrapper
obj.setX(25); //Set value of x in wrapper
alert(obj.getX());

是的,因为我认为你需要做“新建”来创建一个实例。 Javascript不像其他语言那样具有关键字“class”。 这意味着,它取决于您如何使用“函数”。 若你们像你们想的那个样使用它,你们会像函数在obj中返回结果一样使用它。
要将其用作类实例,必须使用new创建实例。

是的,因为我认为创建实例时需要执行“new”。 Javascript不像其他语言那样具有关键字“class”。 这意味着,它取决于您如何使用“函数”。 若你们像你们想的那个样使用它,你们会像函数在obj中返回结果一样使用它。 要将其用作类实例,必须使用new创建实例