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_Nested Function - Fatal编程技术网

JavaScript使用构造函数设置变量

JavaScript使用构造函数设置变量,javascript,variables,nested-function,Javascript,Variables,Nested Function,我试图在构造函数中设置一个可以被嵌套函数表达式调用的变量。不太确定怎么做 var测试=函数(){ var a; 功能测试(a、b、c){ 这个a=a; 这个.b=b; 这个.c=c; } test.getvariableA=函数(){ //不返回应该由构造函数设置的变量 console.log(this.a); }; 回归试验; }(); var t=新测试(“比萨饼”、“意大利面”、“牛排”); //不返回变量 test.getvariableA(); //这将返回变量 控制台日志(t.a)

我试图在构造函数中设置一个可以被嵌套函数表达式调用的变量。不太确定怎么做

var测试=函数(){
var a;
功能测试(a、b、c){
这个a=a;
这个.b=b;
这个.c=c;
}
test.getvariableA=函数(){
//不返回应该由构造函数设置的变量
console.log(this.a);
};
回归试验;
}();
var t=新测试(“比萨饼”、“意大利面”、“牛排”);
//不返回变量
test.getvariableA();
//这将返回变量
控制台日志(t.a)
这将返回变量:
console.log(t.a)

对,因此属性位于
t
实例上

但是您的
test.getvariableA
函数根本不知道
t
!调用
test.getvariableA()
时,它会尝试访问
test.a

您可能希望将方法放在类的原型对象上,而不是构造函数本身。这样,它将被所有实例继承(如
t
),您可以在
t
上调用它以获得
t.a

var test = function() {
  // var a; - this is not used anywhere, drop it

  function test(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;

  }
  test.prototype.getVariableA = function() {
//    ^^^^^^^^^^
    console.log(this.a);
  };
  return test;
}();

var t = new test("pizza", "pasta", "steak");
t.getVariableA(); /*
^ */
console.log(t.a);

这里的问题是在构造函数之外定义
getvariableA
,并将其附加到函数
test
。因此,
getvariableA
是一个“公共”方法,它不指向您创建的
t
实例(或使用
new
关键字创建的任何其他实例)

换句话说,
test.getvariableA
内部的
this
指向函数构造函数本身,而不是该构造函数的任何特定实例(
t

当您将方法附加到构造函数外部的函数时,您可以在不创建新实例的情况下访问它。如果您
console.log(test.getvariableA)
可以看到您可以访问此方法,而无需创建
new
实例,而
console.log(test.a)
显示未定义,因为
a
已分配给类的每个新实例


希望这至少能澄清一点,如果不清楚,很抱歉。

您能使用es6吗?这可能对你有帮助@chevybow Nope。我必须保持结构的原样,而不必进行基于类的声明
newtest
返回什么?尝试重命名变量。在那之后,只需一步一步地检查代码,看看哪里出了问题。