注意點: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); } } }