日期:2014-05-16  浏览次数:20386 次

javascript中模板方法模式的实现
 
<script>
function Panel () {
    this.el = document.createElement('div');
    this.el.style.position = 'absolute';
    this.initPosition();
    this.initStyle();
    document.body.appendChild(this.el);
}
Panel.prototype = {
    initPosition: function () {},
    initStyle: function () {}
}

function LeftPanel () {
    this.base = Panel;
    this.base();
}
LeftPanel.prototype = {
    initPosition: function () {
        this.el.style.left = '0';
    },
    initStyle: function () {
        this.el.style.background = 'red';
        this.el.style.width = this.el.style.height = '100px';
    }
}

function RightPanel () {
    this.base = Panel;
    this.base();
}
RightPanel.prototype = {
    initPosition: function () {
        this.el.style.right = '0';
    },
    initStyle: function () {
        this.el.style.background = 'green';
        this.el.style.width = this.el.style.height = '100px';
    }
}
var leftEl = new LeftPanel();
var rightEl = new RightPanel();
</script>