JavaScript使用构造函数设置变量

Jon*_*mes 0 javascript variables nested-function

我试图在构造函数中设置一个可以由嵌套函数表达式调用的变量.不太确定如何做到这一点

var test = function() {
  var a;

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

  }
  test.getvariableA = function() {
    //not returning a variable that is supposed to be set by the constructor
    console.log(this.a);
  };
  return test;
}();

var t = new test("pizza", "pasta", "steak");
//does not return the variable
test.getvariableA();
//this returns the variable
console.log(t.a);
Run Code Online (Sandbox Code Playgroud)

test.getvariableA();

这应该返回构造函数设置的变量.也许我对另一种语言感到困惑,谢谢你提前帮忙.

Ber*_*rgi 7

这会返回变量: console.log(t.a);

是的,所以属性在t实例上.

但是你的test.getvariableA功能根本不知道t!它test.a在您调用时会尝试访问test.getvariableA().

您可能希望将方法放在类的原型对象上,而不是构造函数本身.这样它将被所有实例(如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);
Run Code Online (Sandbox Code Playgroud)