在javascript中访问兄弟姐妹

时间:2012-05-10 03:14:12

标签: javascript oop node.js

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

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的值。我怎么能做到这一点?

3 个答案:

答案 0 :(得分:1)

它不需要比这更复杂(fiddle):

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

答案 1 :(得分:0)

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

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

答案 2 :(得分: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());