freeze
freeze

Reputation: 566

How to add methods to an instance of the object

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?

Upvotes: 0

Views: 260

Answers (4)

JAB
JAB

Reputation: 21079

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

Upvotes: 0

Craig
Craig

Reputation: 4399

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

Upvotes: 2

Adam Jenkins
Adam Jenkins

Reputation: 55613

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

Upvotes: 0

tobspr
tobspr

Reputation: 8376

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"

Upvotes: 2

Related Questions