0

To get a value like '4,3' I have this:

var value = objeto.row(4).cell(3);

What's the correct form to develop the js method? I suppose I have to do something like that:

function objeto(rowIndex){
   cell: function(cellIndex){
      return rowIndex + ',' + cellIndex;
   }
}

I know it doesn't work, it is only a guess. Thank you...

3
  • Are you asking how to write code so that you can use the syntax in the first bit of code you provided to get "4,3"? Commented Oct 8, 2014 at 13:32
  • 1
    You have to add 2 methods to objeto prototype: row() will set the this.row value and return this, and cell() will return this.row + "," + this.cell. I guess. Commented Oct 8, 2014 at 13:33
  • 1
    you simple forget row, so you need something like this: var objeto = { row : function (rowIndex){ return { cell : function (cellIndex){ return rowIndex+','+cellIndex; }} }} Commented Oct 8, 2014 at 13:38

2 Answers 2

3

yet another way without adding internal function to window

var objeto = { 
    row : function (rowIndex){ 
        return { 
            cell : function (cellIndex){ 
                return rowIndex+','+cellIndex; 
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you'd like to keep a hierarchy where cells belong to rows, you could do this:

var objeto = {
    row: function ( rowIndex ) {
        return ( function ( rowIndex ) {
            this.cell = function ( cellIndex ) {
                return rowIndex + ',' + cellIndex;
            };
            return {
                cell: this.cell
            }
        }( rowIndex ) );
    }
}

4 Comments

this.cell add cell function to window in your case :-)
Please note that you are creating or assigning to the global variable cell whenever the function is called. You should avoid that.
there is no need for the additional closure within the row method. the value of rowIndex is already preserved via the row method, which itself acts as a closure.
You guys are right, I was a bit trigger happy there. Grundy's answer would be the preferred solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.