Since the function name of js is a pointer to the function object, does it refer to memory?
`
var a=function(c){
return ++c;
}
console.log(a(1));
var b=a;
console.log(b(1));
var a=null;
console.log(b);
console.log(b(1));
` , so how to do manual destruction? Do global variables need to be closed before the browser is recycled? Thank you
迷茫2017-05-19 10:28:59
Firstvar a
会在stack
里面开一块空间,然后你将他赋给一个function
,是一个引用类型,于是又在heap
里面又申请一块空间存放function
,此时,stack
里面的a
存放的是function
’s address
And below, the reasons b
赋值给a
,是将stack
里面a
指向的heap
里面function
的地址赋给b
,所以这就是为什么后来a
指向了null
,但是b
仍然指向之前heap
里面function
.
How to destroy? Just change b
也设置为null
or other value. So try not to write global variables for this kind of variables, write local variables.
滿天的星座2017-05-19 10:28:59
Is it a reference to memory? This question is a bit too broad. Data is stored in memory, so it is natural to reference memory
But it is not just as simple as referencing memory. Memory is only responsible for storing data, and the relationship between data cannot be reflected. , so it is not directly referencing the memory
There is hidden processing in the middle. There is a basic theory on how to operate it, but in fact few people know the specific details, it is too low-level
In addition, there are two ways to recycle:
1, 设置null, 等待自动清空
a = null;
会在回收程序执行的时候自动清空
2, 立刻清空
delete a;
直接执行回收
但老ie并不支持这种操作
Generally, just use method 1. Don’t worry about overflow. There are many triggers for automatic recycling, such as timing, such as when the data reaches a certain amount
伊谢尔伦2017-05-19 10:28:59
// 那么在最后应该将 op 解除引用来避免内存泄漏。
// 所谓的内存泄露,就是被分配的内存既不能被使用,也不能够被回收的一个现象。
// 低版本的IE浏览器中,DOM对象与javascript对象形成循环引用,
// 那么就有可能产生内存泄露,除非人为的切断引用。
function box() {
var op = document.getElementById('op');
var text = op.innerHTML;
op.onclick = function () {
alert(text);
};
op = null; //解除引用
}
box();
// 节省内存
// PS:如果并没有使用解除引用,那么需要等到浏览器关闭才得以释放。
黄舟2017-05-19 10:28:59
About the garbage collection mechanism:
Under the old version of IE, the DOM is in the form of a COM object and is cleared using reference counting. If there are circular references, there will never be a chance to release the memory.
In standard browsers, it is the mark clearing method. You only need to manually release the reference and set it to null to release the memory.
If the reference is not dereferenced, the memory will not be released until the execution environment is exited, and the global variable object will not be released until the global execution environment exits, that is, it will not be released until the browser is closed.