2012-05-10 94 views
-3

我在寫一個節點應用程序,我想獲取調用構造函數的變量的名稱。訪問javascript中的兄弟姐妹

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的值。我怎樣才能做到這一點?

+1

'返回this.test;'? – david

+0

當我console.log(this.test)在this.doSomething()它返回未定義。 – devnill

+0

然後您發佈的代碼與您的代碼不匹配。 – david

回答

1

它並不需要成爲任何比這更復雜(fiddle):

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

如果'doSomething'在'constructorFunction.prototype'上,我會給它一個upvote。 – RobG

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

function constructorFunction(){ 
    var self = this; 
    this.test="it works!"; 
    this.doSomething=function(){ 
     return self.test; 
    } 
} 
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());