注意点:javascript
应用场景java
举例: 扫描文件夹性能
/* * * * * * 文件夹(Folder) * * * * * * */ var Folder = function(name) { this.name = name; this.files = []; this.parent = null; } Folder.prototype.add = function(file) { file.parent = this; this.files.push(file); } Folder.prototype.scan = function() { console.log('开始扫描文件夹:' + this.name); var i = 0, len = this.files.length, file; for(; i < len; i++) { file = this.files[i]; file.scan(); } } Folder.prototype.remove = function() { if (!this.parent) { return; } var i = this.parent.files.length - 1, files = this.parent.files, file; for(; i >= 0; i--) { file = files[i]; if (file === this) { files.splice(i, 1); } } } /* * * * * * 文件(File) * * * * * * */ var File = function(name) { this.name = name; this.parent = null; } File.prototype.add = function() { throw new Error('文件下面不能再添加文件'); } File.prototype.scan = function() { console.log('开始扫描文件:' + this.name); } File.prototype.remove = function() { if (!this.parent) { return; } var i = this.parent.files.length - 1, files = this.parent.files, file; for(; i >= 0; i--) { file = files[i]; if (file === this) { files.splice(i, 1); } } }