1、面向委托的设计
2、委托理论
Task = { ???setID:function(ID) {this.id = ID;}, ???outputID:function() {console.log(this.id)};};//让XYZ委托TaskXYZ = object.create(Task);XYZ.prepareTask = function(ID,Label){ ???this.setID(ID); ???this.label = Label;}XYZ.outputTaskDetails = function() { ???this.outputID(); ???console.log(this.label);}//ABC = Object.create(Task);
这段代码中,Task和XYZ并不是类(或者函数),它们是对象。XYZ通过Object.create()创建,它的[[Prototype]]委托了Task对象
相比于面向类(或者说面向对象),这种编码风格称为“对象关联”。我们真正关心的只是XYZ对象(和ABC对象)委托了Task对象
委托者(XYZ,ABC),委托目标(Task)
对象关联风格的代码有一些不同之处:
1、id和label数据成员都是直接存储在XYZ上(而不是Task,)通常来说,在[[Prototype]]委托中最好把状态保存在委托者(XYZ,ABC)而不是委托目标(Task)上
2、在委托行为中,我们会尽量避免在[[Prototype]]链的不同级别中使用相同的命名
要求尽量少使用容易被重写的通用方法名,提倡使用更有描述性的方法名
委托行为意味着某些对象(XYZ)在找不到属性或者方法引用时会把这个请求委托给另一个对象(Task)
委托控件对象:
var Widget = { ???init: function(width,heeight){ ???????this.width = width || 50; ???????this.height = height || 50; ???????this.$elem = null ???}, ???insert:function(){ ???}}var Button = Object.create(Widget);Button.setup = function(width,height,label){ ???// 委托调用 ???this.init(width,height); ???this.label = label || "default"}Button.build = function($where){ ???this.insert();}Button.onClick = function(){}$(document).ready(function(){ ???var $body = $(document.body); ???var btn1 = Object.create(Button); ???btn1.setup(125,30,"hello"); ???btn1.build($body);})
你不知道的js-行为委托
原文地址:https://www.cnblogs.com/lu-yangstudent/p/8044609.html