0

For example I have an instance of some object:

A = function(){};
a = new A();

How to add methods

{b: function(){ console.log('b') },
 c: function(){ console.log('c') }
}

to instance a?

freeze
  • 546
  • 6
  • 16

4 Answers4

2

You should have a look at prototype.

Here is a good explanation about it.

Edit: You can also set the prototype to an array of functions, like that:

var Person = new function() {};

methods = {
    "methodA": function() {alert("method A")},
    "methodB": function() {alert("method B")},                         
}

Person.prototype = methods

p = new Person()
p.methodA(); // Alerts "method A"
Community
  • 1
  • 1
tobspr
  • 8,200
  • 5
  • 33
  • 46
  • Aha, thanks. But how to add a bunch of methods in one operation? – freeze Aug 13 '13 at 11:29
  • Why do you want to add it in one operation? – tobspr Aug 13 '13 at 11:31
  • Your example is adding a methods to object, so if I have already created instance there will no be those methods just prototyped in object. But in my case I can't recreate instance of object, so this example is useless for me... – freeze Aug 13 '13 at 11:40
  • You have to add the methods before you create the first instance – tobspr Aug 13 '13 at 11:42
2

If you want to add methods to an instance, just add them:

a.methodA = function() {
    alert("method A");
};

You can do this with any object. However, you can also add them to the prototype of an instance and this will allow the same methods to be visible on all other instances:

var a = new A(),
    b = new A();

a.prototype.methodA = function() {
    alert("method A");
};

b.methodA();

If you want to add multiple methods in one go, create a mix function or use a framework:

function mix(a, b, typ) {
    var n, o;

    for (n in b) {
        if (! b.hasOwnProperty(n)) continue;

        if (!!(o = b[[n]) && (! typ || typeof o === typ)) {
            a[n] = o;
        }
    }
}

Then...

var a = new A();

mix(a, {
    "methodA": function() {
        alert("method A");
    },
    "methodB": function() {
        alert("method B");
    }
}, "function");
Craig
  • 4,268
  • 4
  • 36
  • 53
0

Prototype is used to add methods to ALL instances of a certain type of object (useful for memory management). If you just want to add methods to only one instance of an object you add them just as you would any property:

var A = function() {
    //......
}

var myA = new A();
myA.methodOne = function() { console.log('called methodOne on myA'); }
myA.methodTwo = function() { console.log('called methodTwo on myA'); }

myA.methodOne();
myA.methodTwo();
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
0

Check out jQuery.extend() if you're okay with using a library/framework.

A = function(){};
a = new A();
d = {b: function(){ console.log('b') },
     c: function(){ console.log('c') }
    };
$.extend(a, d);
JAB
  • 20,783
  • 6
  • 71
  • 80