請勿將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