var o = { x: 'y' }; delete o.x; //此时o会成一个慢对象 o.x; // var o = { x: 'y' }; o = null; //应该这样
在闭包中引入闭包外部的变量时,当闭包结束时此对象没法被垃圾回收(GC)。web
var a = function() { var largeStr = new Array(1000000).join('x'); return function() { return largeStr; } }();
当原有的COM被移除时,子结点引用没有被移除则没法回收。数组
var select = document.querySelector; var treeRef = select('#tree'); //在COM树中leafRef是treeFre的一个子结点 var leafRef = select('#leaf'); var body = select('body'); body.removeChild(treeRef); //#tree不能被回收入,由于treeRef还在 //解决方法: treeRef = null; //tree还不能被回收,由于叶子结果leafRef还在 leafRef = null; //如今#tree能够被释放了。
for (var i = 0; i < 90000; i++) { var buggyObject = { callAgain: function() { var ref = this; var val = setTimeout(function() { ref.callAgain(); }, 90000); } } buggyObject.callAgain(); //虽然你想回收可是timer还在 buggyObject = null; }
Chrome自带的内存调试工具能够很方便地查看内存使用状况和内存泄露:闭包
在 Timeline -> Memory 点击record便可:函数
这个方法用于建立一个对象,并把其prototype属性赋值为第一个参数,同时能够设置多个descriptors,关于decriptor下一个方法就会介绍这里先不说。只须要这样就能够建立一个原型链干净对象了工具
var o = Object.create({ "say": function () { alert(this.name); }, "name":"Byron" });
想明白这两个函数必须明白descriptor是什么,在以前的JavaScript中对象字段是对象属性,是一个键值对,而在ECMAScript5中引入property,property有几个特征this
1. value:值,默认是undefinedspa
2. writable:是不是只读property,默认是false,有点像C#中的constprototype
3. enumerable:是否能够被枚举(for in),默认false调试
4. configurable:是否能够被删除,默认falsecode
一样能够像C#、Java同样些get/set,不过这两个不能和value、writable同时使用
5.get:返回property的值得方法,默认是undefined
6.set:为property设置值的方法,默认是undefined
Object.defineProperty(o, 'age', { value: 24, writable: true, enumerable: true, configurable: true }); Object.defineProperty(o, 'sex', { value: 'male', writable: false, enumerable: false, configurable: false }); console.log(o.age); //24 o.age = 25; for (var obj in o) { console.log(obj + ' : ' + o[obj]); /* age : 25 //没有把sex : male 遍历出来 say : function () { alert(this.name); } name : Byron */ } delete o.age; console.log(o.age); //undefined console.log(o.sex); //male //o.sex = 'female'; //Cannot assign to read only property 'sex' of #<Object> delete o.age; console.log(o.sex); //male ,并无被删除
也能够使用defineProperties方法同时定义多个property,
Object.defineProperties(o, { 'age': { value: 24, writable: true, enumerable: true, configurable: true }, 'sex': { value: 'male', writable: false, enumerable: false, configurable: false } });
这个方法用于获取defineProperty方法设置的property 特性
var props = Object.getOwnPropertyDescriptor(o, 'age'); console.log(props); //Object {value: 24, writable: true, enumerable: true, configurable: true}
获取全部的属性名,不包括prototy中的属性,返回一个数组
console.log(Object.getOwnPropertyNames(o)); //["age", "sex"]