Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/391.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在javascript中检测;“窗口”;[对象窗口]的一部分_Javascript_Node.js - Fatal编程技术网

在javascript中检测;“窗口”;[对象窗口]的一部分

在javascript中检测;“窗口”;[对象窗口]的一部分,javascript,node.js,Javascript,Node.js,在javascript中,检测[对象窗口]的“窗口”部分和/或判断代码是否在节点服务器或浏览器上运行 多一点背景。我正在为nodejs编写一个模块,该模块应该同时在客户端和服务器上运行。我需要在几个地方进行不同的测试,所以我需要检测它在哪里运行。现在我正在将“this”传递给init函数,该函数在服务器上为我提供[object object],在浏览器中为我提供[object Window]。。。但我不知道如何对照窗口/对象部分进行检查。typeof似乎只是检查了前面的“object”部分。思想

在javascript中,检测[对象窗口]的“窗口”部分和/或判断代码是否在节点服务器或浏览器上运行

多一点背景。我正在为nodejs编写一个模块,该模块应该同时在客户端和服务器上运行。我需要在几个地方进行不同的测试,所以我需要检测它在哪里运行。现在我正在将“this”传递给init函数,该函数在服务器上为我提供[object object],在浏览器中为我提供[object Window]。。。但我不知道如何对照窗口/对象部分进行检查。typeof似乎只是检查了前面的“object”部分。思想?
提前感谢

如果您确定将在node.js中收到
[object object]
,并在浏览器中收到
[object Window]
,请检查

var isBrowser = (this.toString().indexOf('Window') != -1);
var isServer = !isBrowser;
字符串的
indexOf
方法检查其参数在该字符串中的位置。返回值
-1
表示该参数不作为子字符串出现

更新

正如其他人建议只检查
窗口
对象的存在,您可以等效地检查浏览器中预期存在的其他对象,如
导航器
位置
。但是,上述建议的此类检查:

var isBrowser = (this.window == this);
将以node.js中的引用错误结束。正确的方法是

var isBrowser = ('window' in this);
或者,正如我所说

var isBrowser = ('navigator' in this);
var isBrowser = ('location' in this);

[对象窗口]
不可靠。一些较旧的浏览器只会说
[object]
[object object]
,而不管对象的类型如何

请尝试以下方法:

var isBrowser = this instanceof Window;
或者,因为我从未使用过Node.js,那么这个呢

var isBrowser = typeof Window != "undefined";

若您只想知道自己是否在节点上运行,只需查看
this===this.window

if (this === this.window) {
    // Browser
} else {
    // Node
}

这比希望
toString
的实现是一致的更可靠,而事实并非如此。

为了简单起见,我认为您无法击败:

if('window' in this) {
    // It's a browser
}

基本上,您正在询问如何在脚本=x中检测Node.js

下面的内容是对underline.js的修改和扩展,我对我的一些客户机/服务器模块代码也使用了一个变量。它基本上扫描node.js特有的全局变量(除非您在client-side=x中创建它们)

这是为了提供一个替代答案,以防它是所有需要的

(function() {
    //this is runned globally at the top somewhere
    //Scans the global variable space for variables unique to node.js
    if(typeof module !== 'undefined' && module.exports && typeof require !== 'undefined' && require.resolve ) {
        this.isNodeJs = true;
    } else {
        this.isNodeJs = false;
    }
})();
或者,如果您只想在需要时调用它

function isNodeJs() {
    //this is placed globally at the top somewhere
    //Scans the global variable space for variables unique to node.js
    if(typeof module !== 'undefined' && module.exports && typeof require !== 'undefined' && require.resolve ) {
        return true;
    } else {
        return false;
    }
};

当然,您首先要检查
窗口是否存在:)如何
this.Window===this
?这会在节点中抛出
引用错误。如果未定义
进程
,则无法使用
If
检查它。使用
进程类型!='未定义“
或其他内容。已更新以反映评论中的讨论。