3

Example: I need create function like object, if i have simple object, i can get it like this:

myObject = function(){
   alert('tada');
}

but i need to implement this function or other param inner object like this:

myObject = {
   value : function(){
      alert('tada!');
   }
};

and call this function only by myObject(), not myObject.value(), thx

  • jQuery is a good example of a function that has methods, which sounds like what you want. – dandavis Dec 08 '14 at 05:49
  • If there are more multiple params like `value`, how do you plan to call those ? I mean `myObject()` would rather work as constructor. What about accessing say `some_other_value_func` ? – SachinGutte Dec 08 '14 at 06:00
  • you can also look into Object.defineProperty(myObject, "valueOf", {value: fn}) – dandavis Dec 08 '14 at 06:05
  • problem was in my bad js knowledge, if i write myObject = { param1: function(){tada!!}}, and later myObject = 'anyParam', myObject will be get 'anyParam', and myObject.param1() will be return 'tada', strange but js not replace object, when i assignment it later. i never seen this practice before in other languages – Maxim Pogorelov Dec 08 '14 at 06:08

4 Answers4

0
MyClass = function(){
  return {
   value : function(){
      alert('tada!');
   }
  }
});

instance = MyClass();
instance.value();

or more appropriately

// Define a class like this
function MyClass(name){
    this.name = name;
}

MyClass.prototype.sayHi = function(){
 alert("hi " + this.name);
}

var instance = new MyClass("mike");
instance.sayHi();
Jerome Anthony
  • 7,823
  • 2
  • 40
  • 31
0

Functions are objects in JavaScript, so you can add properties onto a function. This is okay:

var obj = function() {
    alert("Hello, world");
}
obj.val = "42";
obj() //alerts "hello, world"
Hrishi
  • 7,110
  • 5
  • 27
  • 26
0
obj = {
   myFunc: function(){
      alert('tada');
   }
};
obj = obj.myFunc();

this work for me!

0

myObject = (function() {
  return {
    value: function() {
      alert('tada!');
    }
    `enter code here`
  }
})();

myObject.value();
Arun
  • 11
  • 2