function behavior as property or method depending on how calling it

53 Views Asked by At

i have javascript code as follows:

(function(root, factory) {
  root.test = factory;
})(this, function() {

})
var test = function test(param) {
  var num = 0;
  if (param !== undefined) {
    num += param;
    console.log("calling test added: " + param + ", new value: " + num)
  } else
    console.log("test(without parameter) value:" + num);

  function test2(param) {
    num += param;
    console.log("calling test2 added: " + param + ", new value: " + num)
    return this;
  }

  function test3(param) {
    num += param;
    console.log("calling test3 added: " + param + ", new value: " + num)
    return this;
  }
  return {
    test: this,
    test2: test2,
    test3: test3
  };
}
//this works
test(3).test2(5).test3(7);
//below doesn't
//test.test2(5);

i am not sure question already asked before but i couldnt find similar problem like mine (i found this and that, but not actually what i look for)

i want to access methods of my "test" function without using parentheses like JQUERY' s "$". for example with jquery i can use both ways:

$(...) and $.ajax(...).

in my code i want to use both test(...) and test.test2(...) ways too.

for understanding how jquery achive it, i tried to research in jquery uncompressed development file, but there are too many codes(nearly 10600 lines) and found too complex for me, so i am asking here. I'm sorry for my bad english and Thanks for your help.

0

There are 0 best solutions below