[[prototype]]机制是指对象中的一个内部链接引用另外一个对象,其本质就是对象之间的关联关系(行为委托机制);
面向类设计模式:
// 父类
function Widget(width) {
this.width = width || 50
}
Widget.prototype.render = function($where){
....
}
// 子类
function Button(width) {
// 调用super构造函数
Widget.call(this, width)
}
// 让Button“继承”Widget
Button.prototype = Object.create(Width.prototype)
// 重写render
Button.prototype.render(){...}
// 调用
var btn = new Button(123);
btn.render('dom')
ES6 class语法糖:
class Widget {
constructor(width) {
this.width = width || 50
}
render($where) {...}
}
class Button extends Widget {
constructor(width) {
super(width)
this.width = width
}
render($where) {
super.render($where)
....其他操作
}
onclick() {...}
}
// 调用
var btn = new Button(123);
btn.render('dom')
对象关联风格委托(行为委托模式):倡导直接创建和关联对象,不抽成类,其基于[[prototype]]的行为委托很自然的实现;
var Widget = {
init(width) {
this.width = width
},
render($where){...}
}
var Butoon = Object.create(Widget); // 1.创建新对象;2.[[prototype]]关联到指定对象
Button.setup = function (width) {
// 委托调用
this.init(width)
...其他操作
}
Button.build = function($where) {
// 委托调用
this.render($where)
....其他操作
}
// 调用
var btn = Obejct.create(Button)
btn.setup(123);
btn.build('dom')
行为委托模式:
委托双方均为兄弟关系的对象;
不需要实例化,因为其根本就不是类,只是对象;