0

We have a hypothetical function that concatenates strings:

function Concatenator(){
    //Initializes the concatenator
    this.delimiter = "-"
}

Concatenator.prototype = {
    main_functionality: {
        concatenate: function(array){
            return array.join(this.delimiter)
        }
    }
}

It has to be initialized first (this is a complex process with async stuff). And then afterwards we can call methods in the prototype. However, methods in the prototype reference things created in the init stage, like this.delimiter.

//test it out
myArray = ['one', 'two', 'three'];
c = new Concatenator();
alert(c.main_functionality.concatenate(myArray));

See jsfiddle: https://jsfiddle.net/6j5rgjn3/ As you can see in the jsfiddle, it can call the methods OK but the delimiter is unavailable - it should show one-two-three but instead shows `one,two,three'.

Question: How can c.main_functionality.concatenate reference this.delimiter?

I've tried:

1) calling this.delimiter instead this.prototype.delimiter like so but it doesn't work:

function Concatenator(){
    //Initializes the concatenator
    this.prototype = {}
    this.prototype.delimiter = "-"
}

Concatenator.prototype.main_functionality = {
    concatenate: function(array){
        return array.join(this.delimiter)
    }
}

2) Using .bind(this) after concatenate - no effect.

Any ideas?

LittleBobbyTables
  • 4,361
  • 9
  • 38
  • 67
  • 1
    You can't (easily) do that. Put your methods on the object itself. – SLaks Sep 02 '15 at 20:15
  • I'm confused. Please could you explain what you mean by "put your methods on the object itself"? – LittleBobbyTables Sep 02 '15 at 20:17
  • JS doesn't go down the inheritance chain. In `c.main_functionality.concatenate` call, `c.main_functionality` object is the context of `concatenate`. Sure, you can switch it to `Concatenator.prototype` - but not to the instance of `Concatenator`. So, unless you want to modify the `__proto__` properties in the constructor (but that means changing it for _every_ instances of it), you'd better reorganize your class definition - or use a Module pattern instead. – raina77ow Sep 02 '15 at 20:27
  • An alternative approach would be changing the client code into something like `c.main_functionality.concatenate.call(c, myArray)`, as [here](https://jsfiddle.net/csqf8469/). Still I'm not quite sure why do you need a nesting object - isn't it better to just hide it behind `Concatenator` facade? – raina77ow Sep 02 '15 at 20:31
  • @raina77ow OK I will try that – LittleBobbyTables Sep 02 '15 at 20:35
  • var Concatenator = { delimiter : "-", concatenate : function concatenate(array) { return array.join(this.delimiter); } }; var c = Object.create(Concatenator); console.log(c.concatenate([1,2,3])); – Amerrnath Sep 04 '15 at 10:40

0 Answers0