你可以建立自己的constructor function創建自己窗口對象並在每個實例上存儲DOM元素和數據,例如:
function MyWindow (width, height /*, ...*/) {
var data = {}; // here the data will be stored
// the DOM element
this.element = document.createElement('div');
this.element.className = 'window';
//...
// a method for get and set key/value pairs:
this.data = function (key, value) {
if (typeof value == 'undefined') {
return data[key];
} else {
data[key] = value;
return this;
}
};
}
MyWindow.prototype.sharedMethod = function() {
// shared across all instances, you can access here public members
// like the `this.data` method and the `this.element` DOM element
};
示例us年齡:
var win1 = new MyWindow(300, 200);
win1.data('key1', 'value1').data('key2', 'value2'); // chainable method :)
// to access the DOM element:
win1.element;
// to get the values
win1.data('key1'); // "value1"
win1.data('key2'); // "value2"
var win2 = new MyWindow(300, 200);
win2.data('someData', {foo: 'bar', baz: true});
win2.data('someData').foo; // "bar"
來源
2010-06-10 04:50:53
CMS
歡迎SO,請訪問http://stackoverflow.com/faq – Reigel 2010-06-10 04:34:39