请勿将javascript与java混淆。通过JavaScript你的班级没有私人方法,所以你不能通过使用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
变量没有构造以外的值,因为它们的构造函数的局部变量,而不是方法。
您可以将它们添加到原型,如定义方法:
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
而不是那个。
这是因为'this'不再是识别TestClass,但指定'this'上降(事件,UI) ,加var self = this;在var元素下面,并调用self.methodOne() – Roberrrt
那么我怎样才能从那里调用一个方法? – Daniel
这是'class'关键字的无效使用。它会抛出'Uncaught SyntaxError:Unexpected token ='。你的意思是使用'var' /'let' /'const'吗? – nem035