如何在原生javascript中

时间:2015-04-27 04:34:51

标签: javascript function oop

我正在创建一个js库,直接从集合对象处理项目操作,如下所示。我想允许为每个项添加动态用户定义的对象函数,并通过索引直接使用集合对象使这些函数可用(请参见示例实现)。

var item = function (obj) {
    this.foo = function () {
        alert("foo" + this.name);
    }
    for (var i in obj) {
        this[i] = obj[i]; //dynamic fields (overridable)
    }
}
var collection = function (list) {
    var self=this;
    this.items = [];
    if (list && list.length > 0) {
        for (var i in list) {
            var t = new item(list[i]); // create new item            
            for (var j in t) {
                if (typeof (t[j]) === "function") {
                    this[j]=function(index,arg1,arg2,arg3){                        
                        self.items[index][j](arg1,arg2,arg3); //not working (unreliable)
                        console.log(j) //undefined
                        // problem is here j cannot be visible from function handler.
                        //I need to call dynamic j function within handler
                    }
                }
                this.items.push(t); //push each item into collection
            }
        }
    }
}
var obj=new collection([
    {
        id:1,name:"apple",
        bar:function(arg){
            alert(arg+" "+this.name);
        }
    }
    ]);
    obj.foo(0); //equivalent to obj.items[0].foo();
    obj.bar(0,"parameter"); //equivalent to obj.items[0].bar("parameter");

如上面代码段中的注释所述,我无法动态地从集合函数调用项目函数。 我怎样才能达到这个目的。请帮帮我。

1 个答案:

答案 0 :(得分:1)

您无法从处理程序范围获取相关字段名称。您需要做的是使用字段名称创建新的函数对象,即函数名称=字段名称。为此,您必须在指定项目到集合对象的动态函数时执行一些小技巧。在处理程序范围内,您可以通过arguments.callee来转换函数名称 更改此代码段

var t = new item(list[i]); // create new item            
        for (var j in t) {
            if (typeof (t[j]) === "function") {
                this[j]=function(index,arg1,arg2,arg3){                        
                    self.items[index][j](arg1,arg2,arg3); //not working (unreliable)
                    console.log(j) //undefined
                    // problem is here j cannot be visible from function handler.
                    //I need to call dynamic j function within handler
                }
            }
            this.items.push(t); //push each item into collection
        }

对此:

this.items.push(new item(list[i]));    
        var t=this.items[this.items.length-1];
        for (var j in t) {
           if (typeof (t[j]) === "function") {
                this[j]=new Function( "return function " + j + "(idx,arg1,arg2,arg3){console.log(this.items[idx]);var fn = arguments.callee.toString().substr('function '.length);fn = fn.substr(0, fn.indexOf('(')); if(this.items[idx][fn])this.items[idx][fn](arg1,arg2,arg3);}")();                    
            }
          //  this.items.push(t); //push each item into collection
        }                    
                }

jsfiddle示例:http://jsfiddle.net/kyawlay/7528t7z8/1/