nodejs中的方法和模組的使用
阿新 • • 發佈:2019-02-05
在nodejs中方法的呼叫是怎樣的呢? 一起來愉快的寫程式碼吧 。
var express = require("express");
var app = express();
var hostName = "127.0.0.1";
var port = 8080;
app.all("*",function(req,res,next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept" );
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
function print(){
console.log("這是server3.js中的方法");
}
print();
app.listen(port,hostName,function (){
console.log("伺服器執行成功...");
});
我們定義了一個方法print,直接呼叫之後,觀看我們的後臺輸出。
這樣就在後臺輸出了我們的方法。那麼如何引用其他js檔案中的方法呢?我們新建一個utils.js檔案。
function print(){
console.log("這是utils.js中的print方法");
}
exports.print = print;
在這個js檔案中就只有一個方法,那麼如何使用utils中的print方法呢? 使用方式如下:
require後面的是相對開啟服務的js檔案路徑
var utils = require ("../utils.js");
utils.print();
執行結果
現在想一個問題,utils.js檔案不應該就只有一個方法吧,既然是工具類,自然應該有很多方法才對。那麼要是utils中有多個方法應該如何使用呢?
module.exports ={
"print":function(){
console.log("這是utils.js中的print方法");
},
"toast":function(str){
console.log("toast方法"+str);
}
}
使用方式:
var methodName = "print";
utils[methodName]();
utils.toast("hello");
這裡我使用了兩種方式來呼叫utils中的方法,其中第一種傳入的名稱來呼叫方法,這樣比較靈活,可根據需求自行考量。
關於模組的用法,在上面的案例中已經是使用了,只不過我們匯出的是一個方法。下面我們建立一個Person的模組。
function Person(name,color,age,language){
this.color = color;
this.name = name;
this.age = age;
this.language = language;
this.speak = function(){
console.log(this.name+this.age+this.color+"在講"+this.language);
}
}
module.exports = Person;
這樣就建立好了,其中有四個成員變數和一個speak方法,使用方式.
var Person = require("./Person.js");
var person = new Person("張三","黃種人",18,"漢語");
person.speak();
後臺列印結果:
很顯然,我們做的很成功。下面我們新建一個YellowPerson.js檔案,讓其整合person的所有屬性和方法。
var Person = require("./Person.js");
function YellowPerson(name,color,age,language){
//通過apply方法整合person的屬性和方法
Person.apply(this,[name,color,age,language]);
this.like = function(){
console.log("黃種人喜歡寫程式碼...");
}
}
module.exports = YellowPerson;
使用方式:
var YellowPerson = require('./YellowPerson.js');
var yellowPerson = new YellowPerson("李四","黃種人",20,"漢語");
yellowPerson.speak();
yellowPerson.like();
後臺列印結果:
看到person的方法和yellowperson特有的like方法都打印出來了,至此,我們的模組算是完成啦!