2010-08-24 44 views

回答

1

请参阅YUI widgets中的任何一个。例如,页面上多个YUI增强buttons

创建具有每个实例的数据

的基本技术的多个实例如下所示。

由于调用程序使用new,会为每个小部件创建一个Larry.widget对象的新实例。所以每个小部件都有自己的独立对象“this”并用它来存储每个实例的数据。

同时,该对象的原型包含这些功能。所以所有的小部件都共享相同的功能,但拥有他们的数据集。

Larry = {}; // Create global var 
Larry.widget = function (options) { 
    // create with new. Eg foo = new Larry.widget({an_option: true, id: "q_el"}); 
    // options: object with members: 
    // an_option 
    // id 
    // Then call foo.xyz(); to get the widget to do xyz 
    this.init(options); 
}; 

Larry.widget.prototype = { 
    constructor: Larry.widget, 
    // Setting the constructor explicitly since we're setting the entire 
    // prototype object. 
    // See http://stackoverflow.com/questions/541204/prototype-and-constructor-object-properties/541268#541268 

    init: function(options) { 
    this.id = options.id; 
    this.an_option= options.an_option; 

    this._function_a(); // finish initialization via a function. 
    }, // remember that function init is a member of the object, so separate 
     // the functions using commas 

    _function_a: function() { 
    // This is a "private" function since it starts with _ 
    // Has access to "this" and its members (functions and vars) 
    .... 
    }, 

    xyz: function() { 
    // This is a "public" function. 
    // Has access to "this" and its members (functions and vars) 
    ... 
    } // Note: NO TRAILING COMMA! 
    // IE will choke if you include the trailing comma. 
}   
相关问题