2016-09-28 34 views
0

我想不出寫功能自動計算(構造函數)時node.js中所需的文件..功能自動計算(構造函數)時的node.js

是這樣... file.js

所需的文件
module.exports = { 

    index: function() { 

     //code here 

    } 

}; 

app.js

var file=require("./file"); 
res.send(file.index()); 

我想要什麼......

module.exports = { 

     main :__constructor() 
     { 
     this.name="blabla"; 
     }, 
     index: function() { 

      //code here 
      this.name // will be used this place name variable 

     } 

    }; 

回答

0

使用.prototype()來做到這一點。希望能幫助到你!

const App = function(name) { 
 
    this.name = name 
 
} 
 

 
App.prototype.main = function() { 
 
    return this.name 
 
} 
 

 
b = new App('myName') 
 
console.log(b.main()) 
 

 
//You can do module.exports = App and invoke it in another file

0

okey..but

module.exports = { 

    app :function (name) 
    { 
    this.name="blabla"; 
    }, 
    app.prototype.index: function() { 

} 

}; 

這不起作用!

/var/www/public/nodeapi/app/v1/blog/index.js:19 app.prototype.index:函數(){

const App = function(name) { 
 
    this.name = name 
 
} 
 

 
App.prototype.main = function() { 
 
    return this.name 
 
} 
 

 
b = new App('myName') 
 
console.log(b.main()) 
 

 
//You can do module.exports = App and invoke it in another file

0

喜歡的東西這個?

// file.js 
class MyClass { 
    constructor() { 
    this.name = 'blabla'; 
    } 
    index() { 
    console.log('name', this.name); 
    } 
} 

module.exports = new MyClass(); 
0

班級博客{

constructor() 
{ 

this.name="fookey"; 

} 

index(callback) 
{ 
    var data={}; 
    data.test=this.name; 
    callback(data); 
} 

} 

module.exports=new blog(); 

類型錯誤:未定義

無法讀取屬性 '名' 爲什麼不起作用?