在实例化期间引用属性

时间:2015-05-23 21:33:15

标签: javascript

我试图在javascript中创建一个对象,允许在事件发生时调用函数。在我的程序中,当事件发生时(由keya标识),将调用相应的函数。

function Foo(dict){
   this.add(dict);

   this.biz = 'world';
};

//add a dictionary to the object
Foo.prototype.add = function(dict){
    for(var k in dict){
        //duplicate key check not needed
        this[k] = function(){
            dict[k]();
        }

        this[k].that = this;
    }
};

//call an event
Foo.prototype.call = function(event){
    this[event]();
};

var foo = new Foo(
{
    //'event key':function(){...}
    //Cannot read property 'biz' of undefined
    'test':function(){alert('hello ' + this.that.biz);}
});

foo.call('test'); //expected output: hello world

是否有可能建立一个系统,有人可以使匿名功能的内容参考foo的属性,最好是纯js?

1 个答案:

答案 0 :(得分:0)

好的,首先 - 这是你的代码

function Foo(dict) {
    this.add(dict);
    this.biz = 'world';
};

//add a dictionary to the object
Foo.prototype.add = function(dict) {
    for (var k in dict) {
        // duplicate key check not needed
        this[k] = dict[k];
    }
};

//call an event
Foo.prototype.execute = function(event) {
    this[event]();
};

var foo = new Foo({
    'test': function() {
        alert('hello ' + this.biz);
    }
});

// here this will be pointing to object foo
// that is the instance of Foo and has property baz
foo.execute('test');

如果我理解你的第二个问题 - 答案是肯定的。您可以将对象传递给匿名函数( BTW 这是依赖注入)。

(function(fooLikeObject) {
    ...
    ...fooLikeObject['test']();
    ...
}(foo));