Javascript类变量范围变得未定义
所以我有一个类名Javascript类变量范围变得未定义,javascript,class,Javascript,Class,所以我有一个类名会话 我宣布: function Session() { } 我有一个函数名为:Session.prototype.parseCommand(){} 出于某种原因,如果我将函数调用为:this.parseCommand(),它将被声明为未声明 这也会发生在函数中,例如:This.textInput=false。在某些函数上,我可以调用它,但在其他函数上它是未定义的 有什么问题 function Session() { this.textInput = null;
会话
我宣布:
function Session() {
}
我有一个函数名为:
Session.prototype.parseCommand(){}
出于某种原因,如果我将函数调用为:this.parseCommand()
,它将被声明为未声明
这也会发生在函数中,例如:This.textInput=false
。在某些函数上,我可以调用它,但在其他函数上它是未定义的
有什么问题
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();
}
};
这是完整的代码和错误。我还注意到我不能使用this.linegorth.appendChild(line)代码>而我必须使用document.getElementById('sessionLineGutter').appendChild(line)
。为什么会这样
谢谢,当原型中声明了任何方法时,您不能使用此方法调用它们
它必须通过对象直接调用
函数会话(){
}
session.prototype.method1=函数(){
警报(“此处”);
}
var sess1=新会话();
sess1.method1();
//this-此处指的是窗口对象
显示完整的代码。想必,此
并不是指您在尝试this.parseCommand()
时所期望的对象。请给出一个完整的例子。我们需要的远不止这些。你是怎么开始上课的?您如何调用这些函数。我相信您对javascript分配此会话的方式有问题。prototype.parseCommand(){}
既不是有效语法,也不是调用。添加完整代码我正在调用对象内的函数。对不起,我想我已经很清楚了,它现在已经更新了。当然,你可以在其他方法中使用此调用它们,其中this
是对象?