你不知道的js-行为委托

一、面向委托的设计函数

二、委托理论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);
})
相关文章
相关标签/搜索