2016-03-08 38 views
1

我正在閱讀javascripts的好的部分,並測試了一個代碼。添加一個方法來數字拋出異常

Number.method('integer', function () { 
 
\t document.writeln("called"+ this<0); 
 
return Math[this < 0 ? 'ceiling' : 'floor'](this); 
 
});

,並通過調用它測試它作爲

document.writeln((-10/3).integer()); 

我得到Uncaught TypeError: Math[(intermediate value)(intermediate value)(intermediate value)] is not a function錯誤。難道我做錯了什麼?我對鉻

我忘了提及測試它,還有另一種方法添加到function.protoype作爲

Function.prototype.method = function (name, func) { 
this.prototype[name] = func; 
return this; 
}; 
+1

只是一個小提示:在2016年有什麼理由用'文件撰寫...'調用調試。請了解控制檯及其API:'console.log()'等。 –

回答

2

沒有方法Math.ceiling(),但Math.ceil()。 也許這是產生錯誤:

Uncaught TypeError: Math[(intermediate value)(intermediate value)(intermediate value)] is not a function

1

您需要添加到數

的原型
Number.prototype.integer = function () 
{ 
    document.writeln("called"+ this<0); 
    return Math[this < 0 ? 'ceiling' : 'floor'](this); 
}; 

添加到該原型確保Number的實例將具有此屬性而非Number對象。

另外,儘量避免使用document.writeln,因爲它基本上會清除現有文檔,刪除現有事件。如果需要,使用document.body.innerHTML

Number.prototype.integer = function () 
{ 
    document.body.innerHTML += "<br>called"+ (this<0); 
    return Math[this < 0 ? 'ceil' : 'floor'](this); //observe that ceiling is also replaced with ceil since there is no such method called ceiling 
}; 
+1

沒有方法'Math.ceiling()',但是'Math.ceil()'。 –

+0

@DmitriPavlutin謝謝,我做了更改。 – gurvinder372

+0

@DmitriPavlutin你實際上修復它,謝謝。這是造成問題 – Sam