标签:功能 数据 部分 scan turn font return outer 出版
举例
const Folder = function(name) { this.name = name; this.parent = null; this.files = []; }; Folder.prototype.add = function(file) { file.parent = this; this.files.push(file); }; Folder.prototype.scan = function() { console.log(‘扫描文件夹:‘, this.name); this.files.forEach(file => { file.scan(); }); };
Folder.prototype.remove = function() { if(!this.parent) { // 若为根节点,则不能移除 return; }; this.parent.files.forEach((file, index) => { if(file === this) { file.splice(index, 1); } }); };
const 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; } this.parent.files.forEach((file, index) => { if (file === this) { file.splice(index, 1); } }); };
const folder = new Folder(‘学习资料‘); const folder1 = new Folder(‘Javascript‘); const file1 = new Folder(‘深入浅出node.js‘); folder1.add(new File(‘JavaScript设计模式与开发实践)); folder.add(folder1); folder.add(file); folder1.remove(); folder.scan();
参考文献:
[1] 《JavaScript设计模式与开发时间》,曾探,中国工信出版集团.
标签:功能 数据 部分 scan turn font return outer 出版
原文地址:https://www.cnblogs.com/yijingzheng/p/10231011.html