2016-01-09 106 views
1

我正在嘗試使用Object.prototype進行編寫和學習,並且我收到錯誤,指出在另一種方法中調用this.issue時不是函數。我做錯了什麼導致它通過這個Uncaught TypeError?未捕獲TypeError *不是函數

的JavaScript:

$(document).ready(function() { 
    var Example = function() { 
     this.number1 = null; 
     this.number2 = null; 
    }; 

    Example.prototype.issue = function() { 
     //Logic is here... 
    }; 

    Example.prototype.updateNumber = function() { 
     //more logic is here... 
     this.issue(); 
    }; 

    Example.prototype.updateSign = function() { 
     //logic here... 
     this.issue(); 
    }; 

    (function() { 
     var solution = new Example(); 

    })(); 

}); 

UPDATE:https://jsfiddle.net/czLtc82y/

+0

你能複製它在的jsfiddle?這將更容易找到問題 – Pikamander2

+3

,因爲這是充滿了「僞代碼」,並且您提供的代碼部分是真實的,沒有機會得到答案 –

+2

@ Pikamander2我將立即創建一個 – user3897842

回答

1

在連接到change事件#sign處理器,.number

Example.prototype.newNumber = function(event) { 
    if (event.currentTarget.id === 'number1') { 
     this.number1 = parseFloat($(event.currentTarget).val()); 
    } 
    else { 
    this.number2 = parseFloat($(event.currentTarget).val()); 
    } 
    this.issue(); 
}; 

Example.prototype.newSign = function(event) { 
    this.sign = $(event.currentTarget).val(); 
    this.issue(); 
}; 

this引用#sign.number元素,不new Example objec噸由

var problem = new Example(); 

創建嘗試使用Function.prototype.bind()設置thisnew Example()problem.change()處理程序

(function() { 

    var problem = new Example(); 

    $("#sign").change(problem.newSign.bind(problem)); 

    $(".number").change(problem.newNumber.bind(problem)); 

})(); 

的jsfiddle https://jsfiddle.net/czLtc82y/1/


或者,使用$.proxy()

(function() { 
    var problem = new Example(); 

    $("#sign").change($.proxy(problem.newSign, problem)); 

    $(".number").change($.proxy(problem.newNumber, problem)); 

})(); 

的jsfiddle https://jsfiddle.net/czLtc82y/2/

+2

您可能想了解爲什麼這是必要的。 –

+1

@FelixKling查看更新後的文章 – guest271314

+0

謝謝@ guest271314的答案和解釋! – user3897842

相關問題