-2

so I have a class names Session.

I declare it as:

function Session() {
}

I have a function called as: Session.prototype.parseCommand(){}.

For some reason, if I call the function as: this.parseCommand() it is declared as undeclared.

This also occurs with functions such as: this.textInput = false. On some functions, I can call it, but on others it is undefined.

What is the problem?

function Session() {
    this.textInput = null;
    this.lineGutter = null;
}
Session.prototype.parseCommand = function(command) {
    if (command === 'clear') {

    } else {
        var line = document.createElement('div');
        line.className = 'line';
        line.setAttribute('id', 'line command');
        line.innerHTML = command;
        document.getElementById('sessionLineGutter').appendChild(line);
    }
};
Session.prototype.textInputKey = function(e) {
    if (e.keyCode === 13) {
        this.parseCommand(document.getElementById('sessionText').innerHTML);
        e.preventDefault();
    }
};

Here is the full code and the error. I also notice that I cannot use this.lineGutter.appendChild(line); and instead I have to use document.getElementById('sessionLineGutter').appendChild(line). Why is this?

Thanks,

Corentin Caer
  • 321
  • 3
  • 10

1 Answers1

1

When any method in declared on prototype you cannot call them using this it has to be called directly through the object

function session(){
  }
session.prototype.method1=function(){
  alert("here");
  }
var sess1=new session();
sess1.method1();
//this -here refers to window object

this here refers to window(global) object

In this code snippet

function Session() {
    this.textInput = null;
    this.lineGutter = null;
}

this refers to global(window) object

you can call parsecommand method using var session1=new Session() and it can be called as session1.parseCommand and now inside parseCommand this would be Session object ,so that's why when you are trying to access this.lineGutter.appendChild(line);

It would not happen,because here it is pointing to lineGutter in Session object,but i guess you are expecting it to append to the body which does not happen here because this is an object here

so that's the reason you have to document.getElementById('sessionLineGutter').appendChild(line)

I hope you understand

Geeky
  • 7,420
  • 2
  • 24
  • 50