簡體   English   中英

我無法在javascript中擴展String原型

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM