Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

💪第6期第2题:如何判断当前脚本运行在浏览器还是 node 环境中? #38

Open
LinDaiDai opened this issue Jun 30, 2020 · 0 comments

Comments

@LinDaiDai
Copy link
Owner

如何判断当前脚本运行在浏览器还是 node 环境中?

这道题呆呆其实在很多地方都看到了,但是有的回答好像并不那么靠谱。

回答这道题首先我们需要知道一个概念:

浏览器环境:全局对象为window;而在node环境下,是有一个名为global的对象,它的内部Class属性是为"global"

内部Class属性也就是我们通过Object.prototype.call(obj)这种方式来获取到的内容,比如:

console.log(Object.prototype.toString.call([1, 2, 3])); // "[object Array]"

(关于它的用法呆呆在《【精】从206个console.log()完全弄懂数据类型转换的前世今生(上)》中的toString用法时说的也很详细咯)

因此我们可以得出这种判断方式:

var isBrowser = typeof window !== 'undefined'
    && ({}).toString.call(window) === '[object Window]';

var isNode = typeof global !== "undefined"
    && ({}).toString.call(global) == '[object global]';

({}).toString.call()Object.prototype.toString.call()用法一致,只不过在{}的外面最好加上一个(),也是为了预防JS将大括号{}认为是一个空的代码块(额,呆呆试了一下貌似也没有这方面的问题)。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant