52

Is it like...

var obj = new Object();

obj.function1 = function(){
    //code
}

or something like that?

0

7 Answers 7

92

You can see from the answers that you have already that there is more than one way.

#1
var o = new Object();
o.method = function(){}

#2
var o = new Object();
o.prototype.method = function(){}

#3
function myObject() {
    this.method = function(){}
}
var o = new myObject();

#4
function myObject() {}
myObject.prototype.method = function(){}
var o = new myObject();

#5
var o = {
    method: function(){}
}

#3 and #4 are using a constructor function. this means you can use them to create a number of objects of the same 'class' (classes don't really exist in JavaScript)

#4 is different to #3 because all objects constructed with #4 will share an identical 'method' method because it is a property of their prototype. This saves memory (but only a very tiny amount) and if you change the method of the prototype, all #4 objects will immediately be updated - even if they've already been instantiated.

#1, #2 and #5 are all pretty much equivalent. This is because there will probably only ever be one of them at a time, so the fact that #2 has the method added to the prototype doesn't really matter. (not taking cloning into account)

There are still more ways of adding methods to objects using factories with closure or adding 'static' properties/methods to functions or private nested functions... :)

2
  • How can I define method (for example hasClass) for every HTML element?
    – Ωmega
    Jul 14, 2012 at 16:15
  • 3
    #2 doesn't work. Please remove it from an answer with 72 upvotes :-)
    – Bergi
    Dec 1, 2015 at 12:44
56
var newObj = {
    met1 : function () {
        alert('hello');
    }
};

Then, the method can be called like such :

newObj.met1();

Btw, when declaring a new object, use the object literal ({}), not the new Object() constructor.

2
  • 5
    "when declaring a new object, use the object literal ({}), not the new Object() constructor." - Why's that? Jun 24, 2011 at 13:29
  • 6
    @PaulD.Waite: I believe there is no logical difference, but object literals are more compact, allow setting properties in the same statement, and are generally the more accepted way to do it (stackoverflow.com/q/4597926/1175459).
    – Sean
    Apr 16, 2012 at 17:23
13

Generally use the prototype property:

function YourObject()
{
    //
}

YourObject.prototype.yourMethod= function()
{
   //
}

One thing I haven't seen anyone mention yet is why you might want to use the prototype property over, say, object-literal notation: doing so ensures the function definition gets shared across all instances of the objects created from your function prototype, rather than once per instantiation.

4
  • Uh, no, actually that does not work. You can add methods to an object by adding them to the prototype property of a function and then instantiating it, but not by modifying a property named "prototype" on an instance.
    – Shog9
    Feb 2, 2009 at 20:57
  • 2
    Sorry that's what I meant, yes; I've been coding ActionScript all morning. :) I'll correct. Hey and thanks to whoever downvoted me; appreciate that. Feb 2, 2009 at 20:59
  • Corrected, and removed my down-vote. FWIW, i down-voted you because your example was incorrect and you were at the top of the list - sadly, not everyone bothers to verify that the answer they're upvoting is actually valid.
    – Shog9
    Feb 2, 2009 at 21:07
  • Thanks. And FWIW, I do check my follow-up comments diligently; as soon as I saw yours, I began the correction. Downvoting wasn't necessary. Feb 2, 2009 at 23:05
2

Don't worry bro, here the code is:

  var myObj=function(){
      var value=null

     this.setValue=function(strValue){

     this.value=strValue;
     };

     this.getValue=function(){
     return this.value;
     };    
};

You can call this object like this:

    var obj= new myObj();
    obj.setValue("Hi!");
    alert(obj.getValue());
1

Function.prototype.implement = function(member, value) {
   this[member] = value;
   return this;
}

function MyFunction() {
 //...
}

(function($){

 $.implement("a", "blabla")
 .implement("b", function(){ /* some function */ })
 .implement("c" {a:'', b:''});

})(MyFunction);
1

With es6 you can do it like this:

var a = {
    func(){
        return 'The value';
    }
}
    
document.getElementById('out').innerHTML = a.func();
   
<div id="out"></div>

2
0

You can also do the following instead of using the "Object.create()" method.

Function call:

com.blah.MyChildObj.prototype = createObject(com.blah.MyParentObj.prototype, 
    com.blah.MyChildObj);

Function definition:

function createObject(theProto, theConst) {
    function x() {};
    x.prototype = theProto;
    x.prototype.constructor = theConst;
    return new x();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.