![](/img/trans.png)
[英]Javascript OOP library for client and server-side js (node.js)
[英]how to make a javascript library working in node js for server side operations
我正在嘗試為項目創建一個庫,如下所示:
module.exports = Diary;
function Diary() {
someFunction = function( message ) {
console.log(message)
}
function D() {
return new D._Section;
}
D.about = {
version: 1.0
};
D.toString = function () {
return "Diary "+ D.about.version;
};
var Section = function () {
this.Pages = []
}
D._Section = Section;
//to extend the library for plugins usage
D.fn = sectionproto = Section.prototype = D.prototype;
sectionproto.addPage = function (data) {
this.Pages.push(data)
conole.log(this.Pages)
};
return D;
};
主要目的是為服務器端和客戶端操作使用相同的庫,因此我們可以擁有相同的代碼庫。
這個問題是當我在節點應用程序中使用它時
var Diary = require('./diary.js');
var myDiary = new Diary();
console.log(myDiary.addPage('some text on page'))
並運行它,將引發錯誤TypeError:myDiary.addPage不是一個函數
我不確定要在Node js上執行此操作的方法,因為我們的客戶端應用程序非常龐大,因此如果必須采用其他模式,則需要進行一些更改才能對其進行更改。
第一個問題是:1.這種方法是否正確,還是我們需要研究其他問題?2.如果該方法可以在node js應用程序上運行,那么如何以最少的庫更改
主要問題是您要導出整個Diary
函數,但隨后使用它就像收到了它的返回值( D
函數)一樣。
導出的方式如下:
var Diary = require('./diary.js')();
// Note -------------------------^^
var myDiary = new Diary();
但是請注意,這意味着每次導入都會創建自己的D
函數和關聯的事物。
或者,導出調用Diary
的結果,但是Diary
函數沒有任何作用。
其他問題是:
someFunction
或sectionproto
您就容易成為“隱式全局恐怖 *”的sectionproto
。 確保聲明您的變量。 * (披露:這是我貧乏的小博客上的帖子)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.