0

This code gives me an error:

$(function(){
    var instance = new object();
    literal.call();
});
var literal ={
    call : function(){
        instance.foo();
    }
}
function object(){
    this.selector = $('div');
    this.foo = function(){ this.selector.remove(); }
}

I want to make it run and I want to let the literal object out from $(function(){}). I don't want to change the selector at a later time.

So I discarded this solution

$(function(){
    instance.selector = $('div');
    literal.call();
});
var instance = new object();
var literal ={
    call : function(){
        instance.foo();
    }
}
function object(){
    this.selector = $('div');
    this.foo = function(){ this.selector.remove(); }
}

And I discarded this also

$(function(){
var instance = new object();
var literal ={
    call : function(){
        instance.foo();
    }
}
literal.call();
});
function object(){
    this.selector = $('div');
    this.foo = function(){ this.selector.remove(); }
}

what is the best practice to do this?

4

1 に答える 1

1

問題は、istance変数がレディハンドラーに対してローカルであったことです。(何らかの理由で)コードをそこに移動したくないので、変数をグローバルにする必要があります。

var istance;
$(function(){
    istance = new object();
    literal.call();
});
var literal = {
    call: function() {
        istance.foo();
    }
}
function object(){
    this.selector = $('div');
    this.foo = function(){ this.selector.remove(); }
}
于 2012-12-05T20:39:45.630 に答える