微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JS设计模式: 访问者模式

var Visitor = function() {
    return {
        splice : function() {
            var args = Array.prototype.splice.call(arguments,1);
            Array.prototype.splice.apply(arguments[0],args);
        },push : function() {
            var len = arguments[0].length || 0;
            var args = Array.prototype.splice.call(arguments,1);
            arguments[0].length = len + arguments.length - 1;
            return Array.prototype.push.apply(arguments[0],pop : function() {
            return Array.prototype.pop.apply(arguments[0]);
        }
    }

}();

var a = new Object();
Visitor.push(a,1,2,3,4);
console.log(a);

Visitor.push(a,4,5,6);
console.log(a);
Visitor.pop(a);
console.log(a);
Visitor.splice(a,2);
console.log(a);

输出

{ '0': 1,'1': 2,'2': 3,'3': 4,length: 4 }
{ '0': 1,'4': 4,'5': 5,'6': 6,length: 7 }
{ '0': 1,length: 6 }
{ '0': 1,length: 2 }

适合于数据稳定,数据操作方法易变的环境。(例子中a对象不具备push等方法,通过 Array.prototype.push.apply(arguments[0],args);调用时,args必须是数组)
更具事先约定的变量顺序,划分变量类型,进行相应操作。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐