user1392191
user1392191

Reputation: 117

Javascript object instance and document ready

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?

Upvotes: 0

Views: 1004

Answers (1)

Bergi
Bergi

Reputation: 664620

Your problem is that the istance variable was local to the ready handler. As you don't want to move your code in there (for whatever reasons), you will need to make the variable global:

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(); }
}

Upvotes: 1

Related Questions