Pascal Bayer
Pascal Bayer

Reputation: 2613

JS anonymous functions

my problem is that I want to call a function like:

$('div').doSomething('xyz');

and my js-code is:

var $ = function(element) {
    var doSomething = function(xyz, xzy, zxy) {
        alert(xyz + element);
    };
};

but that does not work (I'm new to js anonymous functions), where's the error?

Thanks for help!

Upvotes: 0

Views: 172

Answers (1)

NickAldwin
NickAldwin

Reputation: 11754

Try

var $ = function(element) {
    // if the function is called without being called as a constructor,
    // then call as a constructor for us.
    // (partially borrowed from http://stackoverflow.com/questions/4556110/creating-a-jquery-like-object )
    if (this.constructor !== $) {
        return new $(element);
    }
    this.doSomething = function(txt) {
        alert(txt + element);
    };
};

Upvotes: 1

Related Questions