JS匿名函数

时间:2010-12-30 16:36:27

标签: javascript html anonymous-function anonymous

我的问题是我想调用类似的函数:

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

我的js代码是:

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

但这不起作用(我是js匿名函数的新手),哪里出错?

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

尝试

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