一、面向委託的設計函數
二、委託理論ui
Task = { setID:function(ID) {this.id = ID;}, outputID:function() {console.log(this.id)}; }; //讓XYZ委託Task XYZ = 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對象this
相比於面向類(或者說面向對象),這種編碼風格稱爲「對象關聯」。咱們真正關心的只是XYZ對象(和ABC對象)委託了Task對象編碼
委託者(XYZ,ABC),委託目標(Task)spa
對象關聯風格的代碼有一些不一樣之處:設計
一、id和label數據成員都是直接存儲在XYZ上(而不是Task,)一般來講,在[[Prototype]]委託中最好把狀態保存在委託者(XYZ,ABC)而不是委託目標(Task)上code
二、在委託行爲中,咱們會盡可能避免在[[Prototype]]鏈的不一樣級別中使用相同的命名對象
要求儘可能少使用容易被重寫的通用方法名,提倡使用更有描述性的方法名blog
委託行爲意味着某些對象(XYZ)在找不到屬性或者方法引用時會把這個請求委託給另外一個對象(Task)get
委託控件對象:
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); })