Coli
Coli

Reputation: 1023

Object literal in object with prototypes, with funtion parameters

I have an object with a function inside and an object literal:

function SomeThing() {
    var self = this;
    self.publicFunction = function() {...}

    self.choose = function(data) {
        var script = {
            one: self.one,
            two: self.two,
        };
        return (script[data.type])(data);
    };
};
SomeThing.prototype.one = function one(data) {
    console.log(this);
    this.publicFuntion();
    ...
};
...

I need to pass some parameters to the functions appended with prototype. But when I do so return ...(data) the publicFuntion inside is not reachable.

var some = new SomeThing();
some.choose(data); // data.type === 'one'
// -> undefined
// -> Cannot read property 'publicFunction' of undefined.

How can I use public functions inside of the prototypes or pass parameters in the object literal?

Upvotes: 1

Views: 27

Answers (1)

Bergi
Bergi

Reputation: 665564

You're calling the method on the script object, not the SomeThing instance. Use either call to set the receiver explicitly

…choose = function(data) {
    var script = {
        one: self.one,
        two: self.two,
    };
    return script[data.type].call(self, data);
};

or just drop the script object and directly use

…choose = function(data) {
    if (["one", "two"].includes(data.type))
        return self[data.type](data);
};

Upvotes: 1

Related Questions