天天看點

js回憶錄(1)——變量,null 和 undefined

作者:Zl子龍

變量:這個東西不同的高度的人看法不一樣,甚至不同領域的人的看法也不一樣,當初上機組的時候依稀記得老師說這個寄存器那個鎖存器什麼的,然後根據高低電位就變成了二進制認識的0和1了,當然了具體細節本部落客大人也不知道!而在我現在看來,變量就是一個容器,你用什麼就向記憶體提出申請,這個叫做變量聲明,至于到底要幹什麼你就用指派告訴電腦吧。

js把變量類型大緻分為 引用類型和簡單類型,通過typeof運算符又可分為:object,function,number,string,boolean,undefined(初學者不要把undefined視為類型不然容易混淆一些概念),通過instanceof運算符又可以判斷出正則,,array,promise等等東西。這些都不重要,重要的是你隻要知道引用類型和簡單類型的特性就行了,引用類型引用同一個記憶體裡邊的東西,是以引用了相同對象的變量隻要一個變了其他的也會跟着變,而簡單類型在這一點和引用類型是不同的。然後es6裡邊新加了個叫const的東西,鎖定了變量的入口位址,使得變量隻要聲明為某一類型之後,以後就不會變動了。你非作死改變他的值/引用的話就會抛出錯誤。

然後變量聲明會提升,注意js裡的作用域鍊。

總的來說,浏覽器通路某一屬性/值,是就近取值的,css如此js也可以大緻如此了解。

undefined: 變量未聲明前是undefined,聲明了沒指派是undefined,

null: 記憶體中和引用類型差不多,

20180411新增一條:

浏覽器環境下undefined是window的undefined,null就是null,原型鍊的終點

所謂 道生一 一生二 二生三 三生萬物,js裡的道大概是null

然後當一個變量為null或undefined的時候指派或者讀取屬性的時候是會出錯的。。。

變量差不多就這些内容了,最後說一點js的記憶體管理機制吧。

關于記憶體管理,有引用計數垃圾收集和标記-清除兩個算法。

引用計數垃圾收集:這是最簡單的垃圾收集算法。此算法把“對象是否不再需要”簡化定義為“對象有沒有其他對象引用到它”。如果沒有引用指向該對象(零引用),對象将被垃圾回收機制回收。該算法有個限制:無法處理循環引用。比如下面的例子:

function f(){
  var o = {};
  var o2 = {};
  o.a = o2; // o 引用 o2
  o2.a = o; // o2 引用 o
  return "azerty";
 }
  f();
           

當f執行完畢之後,這兩個對象不會離開f的作用域,是以這時候o和o2已經可以被回收了,但是他們之間存在循環引用,故而引用計數算法考慮到它們互相都有至少一次引用,是以它們不會被回收,是以就造成記憶體洩漏了。

IE 6, 7 使用引用計數方式對 DOM 對象進行垃圾回收。該方式常常造成對象被循環引用時記憶體發生洩漏。

--引用自 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Memory_Management

标記-清除算法:

This algorithm reduces the definition of "an object is not needed anymore" to "an object is unreachable".

This algorithm assumes the knowledge of a set of objects called roots (In JavaScript, the root is the global object). Periodically, the garbage-collector will start from these roots, find all objects that are referenced from these roots, then all objects referenced from these, etc. Starting from the roots, the garbage collector will thus find all reachable objects and collect all non-reachable objects.

This algorithm is better than the previous one since "an object has zero reference" leads to this object being unreachable. The opposite is not true as we have seen with cycles.

As of 2012, all modern browsers ship a mark-and-sweep garbage-collector. All improvements made in the field of JavaScript garbage collection (generational/incremental/concurrent/parallel garbage collection) over the last few years are implementation improvements of this algorithm, but not improvements over the garbage collection algorithm itself nor its reduction of the definition of when "an object is not needed anymore".

--引用自 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Memory_Management

簡而言之js裡全局對象無法通路到的東西都會被回收,這個算法要比前一個算法好,并且在2012之後的現代浏覽器上已經的得到了支援。

繼續閱讀