How to change object property in JavaScript parameters

Example: I need to create a function as an object, if I have a simple object, I can get it like this:

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

      

but I need to implement this function or other internal param object like this:

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

      

and call this function only myObject()

, not myObject.value()

, thanks

+3


source to share


4 answers


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

      

0


source


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



var obj = function() {
    alert("Hello, world");
}
obj.val = "42";
obj() //alerts "hello, world"

      

0


source


obj = {
   myFunc: function(){
      alert('tada');
   }
};
obj = obj.myFunc();

      

this work for me!

0


source


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

myObject.value();
      

Run codeHide result


0


source







All Articles