[英]I can't extend the String prototype in javascript
這是代碼
<script>
String.prototype.testthing = function() {
return "working";
}
alert(String.testthing());
</script>
當我打開此頁面時,我收到以下錯誤
Uncaught TypeError: Object function String() { [native code] } has no method 'testthing'
我無法弄清楚為什么。 我已經擴展了Array原型而沒有任何問題。
您正確顯示的代碼擴展了String
原型。 但是,您嘗試使用String.testthing
在函數上調用方法,而不是在string
實例上調用。
alert("".testthing()); // "displays 'working'
如果您確實想要從String
構造中調用方法,那么您需要在Function
上擴展原型
Function.prototype.testthing = function () {
return "working";
}
alert(String.testthing());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.