开发者

jQuery as function and Object, i.e. $() and $.()

开发者 https://www.devze.com 2023-03-21 22:33 出处:网络
How can a global object be programmed to be treated as a function and a开发者_开发百科 object? Just like jQuery does (if I am correct?)

How can a global object be programmed to be treated as a function and a开发者_开发百科 object? Just like jQuery does (if I am correct?)

For example:

 X.foo = '';

and

 X('bar');


You simply define X and X.foo as you normally would, like this:

var X = function(a)
{
    return a * 2;
}
X.foo = function(a)
{
    return a + 1;
}

console.log(X(10));
console.log(X.foo(10));

Results in:

20
11


Functions in JavaScript are objects like any other and can have arbitrary properties. For example:

function Test() {}

Test.someProp = "test";

You might think of these as class variables, depending on your point of view.

Witness:

Test instanceof Object // true


function X(string){
    alert(string);
}

X.foo = 10;
alert(X.foo); // Alerts "10"
X('bar');     // Alerts "bar"


Every function is an object in Javascript:

function f(x) {
    console.log(x);
}
f.foo = 1;
f('bar'); // 'bar
console.log(f.foo); // 1


function X(name)
{
    if (name == 'bar')
    {
        // do so mething
    }
}
X.foo = "hello!";

Functions are objects in Javascript.


function foo(txt){

    alert(txt)

}
foo.text="bar"
alert(foo.text)       //will give you "bar"
foo("bar")            //will give you "bar" also
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号