首页 > 在javascript中,如何判断运行环境?

在javascript中,如何判断运行环境?

我准备使用mean(mongodb+express+angular+nodejs)开发一个应用,并建立一套框架将前端与后端之间的界限模糊起来。这里遇到一个问题,有时候前后端的代码可能会放在同一个文件里,这时怎么通过javascript判断目前代码的运行环境是前段还是后端呢?


(function(){
    var root=this,
        isBrowserSide=false;
    if(typeof window !=="undefined" && root===window){
        isBrowserSide=true;
    }
}).call(this);

以async库为例,该库可以在浏览器或者node.js中使用

var root = this
// AMD / RequireJS
if (typeof define !== 'undefined' && define.amd) {
    define([], function () {
        return async;
    });
}
// Node.js
else if (typeof module !== 'undefined' && module.exports) {
    module.exports = async;
}
// included directly via <script> tag
else {
    root.async = async;
}
【热门文章】
【热门文章】