类与对象 创建 UI 控件
不使用任何“类”辅助库或者语法的情况下,使用纯JavaScript 实现类风格的代码:
function Widget(width, height) {
this.width = width || 50;
this.height = height || 50;
this.$ele = null;
}
Widget.prototype.render = function($where) {
if (this.$ele) {
this.$ele.css({
width: this.width + "px",
height: this.height + "px"
}).appendTo($where);
}
};
function Button(width, height, label) {
Widget.call(this, width, height);
this.label = label || "Default";
this.$ele = $("button").text(label);
}
Button.prototype = Object.create(Widget.prototype);
Button.prototype.render = function($where) {
Widget.prototype.render.call(this, $where);
this.$ele.click(this.onClick.bind(this));
};
Button.prototype.onClick = function(e) {
console.log("Button" + this.label + "cilcked");
};
$(document).ready(function() {
var $body = $(document.body);
var btn1 = new Button(50, 30, "Hello");
var btn2 = new Button(50, 30, "World");
btn1.render($body);
btn2.render($body);
});
ES6语法糖
class Widget {
constructor(width, height) {
this.width = width || 50;
this.height = height || 50;
this.$ele = null;
}
render($where) {
if (this.$ele) {
this.$ele.css({
width: this.width + "px",
height: this.height + "px"
}).appendTo($where);
}
}
}
class Button extends Widget {
constructor(width, height, label) {
super(width, height);
this.label = label || "Default";
this.$ele = $("button").text(this.label);
}
render($where) {
super.render($where);
this.$ele.click(this.onClick.bind(this));
}
onClick(e) {
console.log("Button" + this.label + "cilcked");
}
}
$(document).ready(function() {
var $body = $(document.body);
var btn1 = new Button(50, 30, "Hello");
var btn2 = new Button(50, 30, "World");
btn1.render($body);
btn2.render($body);
})
事件委托
var Widget = {
init(width, height) {
this.width = width;
this.height = height;
this.$ele = null;
},
render($where) {
if (this.$ele) {
this.$ele.css({
widht: this.width + "px",
height: this.height + "px"
}).appendTo($where);
}
}
};
var Button = Object.create(Widget);
Button.setup = function(width, height, label) {
this.init(width, height);
this.label = label;
this.$ele = $("button").text(label);
};
Button.build = function($where) {
this.render($where);
this.$ele.click = this.onClick.bind(this);
};
Button.onClick = function(e) {
console.log("Button" + this.label + "cilcked");
};
$(document).ready(function() {
var $body = $(document.body);
var btn1 = Object.create(Button);
btn1.setup(50, 30, "Hello");
var btn2 = Object.create(Button);
btn2.setup(50, 30, "World");
btn1.render($body);
btn2.render($body);
});