2016-08-21 28 views
0

的不同方法的方法,我得到這個代碼:的JavaScript OOP - 調用同一類

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

任何想法,爲什麼?

+1

這是因爲'this'不再是識別TestClass,但指定'this'上降(事件,UI) ,加var self = this;在var元素下面,並調用self.methodOne() – Roberrrt

+0

那麼我怎樣才能從那裏調用一個方法? – Daniel

+2

這是'class'關鍵字的無效使用。它會拋出'Uncaught SyntaxError:Unexpected token ='。你的意思是使用'var' /'let' /'const'嗎? – nem035

回答

1

請勿將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; 
      } 
     }); 
    } 
}; 

但要注意的是,methodOnemethodTwo變量沒有構造以外的值,因爲它們的構造函數的局部變量,而不是方法。

您可以將它們添加到原型,如定義方法:

TestClass = function() {}; 
TestClass.prototype = { 
    constructor: TestClass, 
    methodOne: function(){...}, 
    methodTwo: function(){...} 
}; 

在這種情況下,如果你從methodTwo致電methodOnethis關鍵字的工作,但在你的例子,你從一個函數調用它在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而不是那個。

1

幾點提高:

  1. 的ES6類的語法是不同的。

  2. 您可以使用bindthis對象修復爲指定給drop的功能。

  3. 與問題無關,但該函數中的if確實沒有必要。你可以只返回布爾表達式的結果:

代碼:

class TestClass { 
    methodOne (a, b) { 
     return (a == b); 
    } 

    methodTwo() { 
     var elements = $('.element'); 

     elements.droppable({ 
      drop: function(event, ui) { 
       return this.methodOne(ui.draggable.data('a'), ui.draggable.data('b')); 
      }.bind(this) 
     }); 
    } 
}; 
+0

Yepp,目前還不清楚他是否想使用ES5或ES6,語法是它們之間的一半。由於他使用的是DOM,在這個問題上沒有babel標籤,所以我猜他正試圖在瀏覽器中使用ES5。 – inf3rno