-3

我正在编写一个节点应用程序,我想获取调用构造函数的变量的名称。

a=new constructorFunction();
b=new constructorFunction();

function constructorFunction(){
    this.test="it works!";
    this.doSomething=function(){
       //this should return the contents of this.test
    }
}

console.log(a.doSomething());
console.log(b.doSomething());

正如评论所说,我想返回 a.test 和 b.test 的值。我怎样才能做到这一点?

4

3 回答 3

1

它不需要比这更复杂(小提琴):

function constructorFunction() {
  this.test="it works!";
  this.doSomething = function() {
    return this.test;
  }
}
于 2012-05-10T03:18:35.307 回答
0
a=new constructorFunction();
b=new constructorFunction();

function constructorFunction(){
    var self = this;
    this.test="it works!";
    this.doSomething=function(){
       return self.test;
    }
}
于 2012-05-10T03:18:38.817 回答
0

在 chrome 中这有效......(V8 所以我假设 node.js 会表现相同)

http://jsfiddle.net/zTTZR/1/

a=new constructorFunction();
b=new constructorFunction();

function constructorFunction(){
    this.test="it works!";
    this.doSomething=function(){
       return this.test;
    }
}

console.log(a.doSomething());
于 2012-05-10T03:18:46.383 回答