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

root 对象初始化 #1

Open
zhangxiang958 opened this issue Sep 6, 2017 · 3 comments
Open

root 对象初始化 #1

zhangxiang958 opened this issue Sep 6, 2017 · 3 comments

Comments

@zhangxiang958
Copy link
Owner

从头开始阅读源码:

使用 IIFE

underscore 将所有函数封装在一个 IIFE 里面, 避免污染全局对象:

(function(){
    
}());

第一行代码:

var root = typeof self == 'object' && self.self === self && self || 
          typeof global == 'object' && global.global === global && global ||
          this ||
          {};

self

第一行代码就有所收获, self 是 window.self, self 属性是对窗口的自身的只读引用, 经常会使用 self 来代替 window 对象. 在防 HTTP 劫持的时候就会使用 window.top 是不是等于 window.self 来判断是不是被劫持了. 第一行的意思就是判断代码是不是在客户端下运行也就是 window 对象里面, 如果 self 是一个对象而且 self.self === self 的话那么就说明是在浏览器端, 就将 self 值传给 root, 相当于下面:

var root = typeof self == 'object' && self.self === self && self;

// var root = true && true && self;  
// ==> 
// var root = self;

global

global 是 node 环境下的全局对象的引用, 类似于 self, global.global === global 的话就说明是 node 环境下, 那么就是:

var root = typeof global == 'object' && global.global && global;

// var root = true && true && global;
// ==>
// var root = global;

this

如果都不是那么就是在其他的一些 js 环境里面比如 web worker, 你可以在浏览器里面试试, 打印出来的 this 是 worker 对象:

new Worker('console.log(this);');  //  Worker { onmessage: null, onerror: null }

所以 root 用这个 this 对象.如果最后连 this 对象都不存在, 那么就让 root 值为一个对象.

@ghost
Copy link

ghost commented Sep 25, 2017

lodash都已经出到4.17.4了,为什么你这分析还是1.x的?

@zhangxiang958
Copy link
Owner Author

@ningbo16 我阅读的是 underscore.js 的 1.8.3 版本哦,是目前 github 仓库最新的版本

@ghost
Copy link

ghost commented Sep 25, 2017

尴尬,自己眼花了,我是自己想看下lodash的,下意识中把它俩当作一样的了

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