2013-07-15 80 views
3

方法錯誤我使用下面的代碼,但它返回以下錯誤對象有沒有在JavaScript

Uncaught TypeError: Object [object HTMLAnchorElement] has no method 'userInput' 

這裏是代碼jsfiddle

var ClickEvent = function (event) { 
    this.ev = $('.' + event); 
    this.ev.on('click', function() { this.userInput(); }); 
}; 

ClickEvent.prototype = function() { 
    return { 
     userInput: function() { 
      console.log('user'); 
     }, 

     show: function() { 
      console.log('show'); 
     } 
    }; 
}(); 

var c = new ClickEvent('event'); 

我打電話userInput函數內部on()回調函數,但返回error以上。

我該如何解決這個問題?

+0

在click事件處理程序函數(您現在有userInput的地方)中放置了一個'console.log(this)'。它告訴你什麼? :) –

+0

是'$'jQuery?如果是,請添加標籤。 – epascarello

回答

5

問題是點擊回調處理程序中的執行上下文(this)沒有指向ClickEvent實例,它引用了被單擊的dom元素。

您需要使用

this.ev.on('click', $.proxy(function() { this.userInput(); }, this)); 

演示:Fiddle

var that = this; 
this.ev.on('click', function() { that.userInput(); }); 

演示:Fiddle

2

this.userInput()嵌套在回調函數中,因而內作用域它。你可以外部化this情況下,你需要如下:

var ClickEvent = function (event) { 
    var $this = this; 
    $this.ev = $('.' + event); 
    $this.ev.on('click', function() { $this.userInput(); }); 
}; 
+0

$ this是什麼意思?我的意思是這個變種=這個;不同於var $ that = this; ? – 2619

+0

@ x4ph4r不,沒有什麼區別,'$ this'只是一個變量的名稱,就像'that'。 – sp00m

0

"this"onclick函數內部引用"this.ev"這是

"$('.' + event);" 

"userInput""show"你的對象。