Agustin Castro
Agustin Castro

Reputation: 459

prototype vs apply in javascript

If I need a object into another for use in a function, which is the best?

function A() {

    this.alert = function () {
        console.log(b.value);
    }

    this.alert2 = function () {
        console.log(this.value);
    }
}

function B() {
    this.value = 'test';
}

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

A.prototype.b = b;

// Option 1
`a.alert();`

// Option 2
`a.alert2.apply(b);`

I believe option 2 is better because only use the object (b) in one function.

Upvotes: 0

Views: 77

Answers (2)

Kevin
Kevin

Reputation: 149

There isn`t a best option, its about what you have to do.

The first option by putting b in its prototype makes A to be more coupled to b.

The 2nd one you are changing its contests.. you need to know what the function does, if you don`t have the documentation you may pass an object wich doesnt has a property needed for the function, so that is not a good choice to make an api for example.

Algo wouldn`t it be happier to set this.alert to a function which receives a parameter?

It all depende on your needs...

Upvotes: 0

Bergi
Bergi

Reputation: 664425

The prototype is much easier, but I'd use it the other way round:

function B() {
    this.value = 'test';
}
B.prototype.alert = function() {
    console.log(this.value);
}
var b = new B();
b.alert();

If you want to use a function/method of a different object, you should give it a parameter (instead of using an implicit global b variable like in your a.alert function):

var a = {
    alert: function(x) {
        console.log(x.value);
    }
};
a.alert(b);

or inherit from it when you have a method, like:

var a = {
    value: "a test",
    alert: function() {
        console.log(this.value);
    }
};
// =============================
function B() {
    this.value = 'test';
}
B.prototype.alert = a.alert; // mixin inheritance
var b = new B();
b.alert();

Upvotes: 4

Related Questions