加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 创业 > C语言 > 正文

JS设计模式: 访问者模式

发布时间:2020-12-15 00:30:48 所属栏目:C语言 来源:网络整理
导读: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.prot
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必须是数组)
更具事先约定的变量顺序,划分变量类型,进行相应操作。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读