我得到了这个代码:
class TestClass = function() {
var methodOne = function(a, b) {
return (a == b);
}
var methodTwo = function() {
var elements = $('.element');
elements.droppable({
drop: function(event, ui) {
if (!this.methodOne(ui.draggable.data('a'), ui.draggable.data('b'))) {
return false;
}
return true;
}
});
}
};
运行此程序时,出现以下错误:
Uncaught TypeError: this.methodOne is not a function
有什么想法吗?
最佳答案
不要将 javascript 与 java 混淆。通过 javascript,您的类没有私有(private)方法,因此您无法使用 this
关键字访问这些函数。
您可以执行以下操作:
var TestClass = function() {
var methodOne = function(a, b) {
return (a == b);
}
var methodTwo = function() {
var elements = $('.element');
elements.droppable({
drop: function(event, ui) {
if (!methodOne(ui.draggable.data('a'), ui.draggable.data('b'))) {
return false;
}
return true;
}
});
}
};
但请注意,methodOne
和 methodTwo
变量在构造函数之外没有值,因为它们是构造函数的局部变量而不是方法。
您可以通过将方法添加到原型(prototype)来定义方法,例如:
TestClass = function() {};
TestClass.prototype = {
constructor: TestClass,
methodOne: function (){...},
methodTwo: function (){...}
};
在这种情况下,如果您从 methodTwo
调用 methodOne
,则 this
关键字有效,但在您的示例中,您从函数调用它在 methodTwo
中定义,因此您必须使用 bind()
函数来创建一个包装器,通过该函数设置上下文。
var TestClass = function() {
};
TestClass.prototype = {
constructor: TestClass,
methodOne: function(a, b) {
return (a == b);
},
methodTwo: function() {
var elements = $('.element');
elements.droppable({
drop: function(event, ui) {
if (!this.methodOne(ui.draggable.data('a'), ui.draggable.data('b'))) {
return false;
}
return true;
}.bind(this)
});
}
};
如果你想使用 ES6 类而不是 ES5,那么情况会有所不同,但你需要一个编译器,例如babel、traceur 等...据我所知,ES5 不能使用 class
关键字,因此您应该使用 var
而不是它。
关于Javascript OOP - 从同一类的不同方法调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39062031/