JS设计模式: 访问者模式

前端之家收集整理的这篇文章主要介绍了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必须是数组)
更具事先约定的变量顺序,划分变量类型,进行相应操作。

猜你在找的程序笔记相关文章