萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript String.prototype 擴充方法完整指南

前言

JavaScript 內建物件的 prototype 屬性允許我們為所有字串實例一次性新增方法。本文彙整實務常用的字串擴充方法,並說明 prototype 運作機制與注意事項。

常用字串擴充方法庫

// 1. 計算中英文混合長度(中文算 2 字元)
String.prototype.ChineseLength = function() {
    return this.replace(/[^\x00-\xff]/g, "**").length;
};

// 2. 判斷是否以指定字串結尾
String.prototype.EndsWith = function(str) {
    return this.substr(this.length - str.length) === str;
};

// 3. 去除左側空白
String.prototype.LeftTrim = function() {
    return this.replace(/^\s*/, "");
};

// 4. 去除右側空白
String.prototype.RightTrim = function() {
    return this.replace(/\s*$/, "");
};

// 5. 判斷是否以指定字串開頭
String.prototype.StartsWith = function(str) {
    return this.substr(0, str.length) === str;
};

// 6. 去除雙側空白(ES5 已內建 trim,此為相容寫法)
String.prototype.Trim = function() {
    return this.replace(/^\s*|\s*$/g, "");
};

使用範例

var msg = "  Hello 中文  ";
console.log(msg.ChineseLength()); // 13
console.log(msg.Trim());          // "Hello 中文"
console.log(msg.StartsWith("He")); // true
console.log(msg.EndsWith("文"));   // true

進階:覆寫內建方法與自定方法

// 新增自定方法
String.prototype.myMethod = function() {
    return "my define method";
};

// 覆寫 toString
String.prototype.toString = function() {
    return "my define toString method";
};

var s = new String("foo");
console.log(s.myMethod()); // "my define method"
console.log(s.toString()); // "my define toString method"
console.log("foo".toString()); // "my define toString method" (字面值也受影響)

關鍵觀念釐清

  1. 內建物件 prototype 唯讀:無法將 String.prototype 整個重新指派為新物件(如 String.prototype = new Employee()),否則原有方法全失,且實例無法存取新原型屬性。
  2. 自訂物件可替換 prototype:僅限自訂建構函式。
  3. isPrototypeOf():檢查物件是否存在於另一物件的原型鏈中。
    function Person() { this.name = "Rob"; }
    function Employee() { this.dept = "HR"; }
    Employee.prototype = new Person();
    var ken = new Employee();
    console.log(Person.prototype.isPrototypeOf(ken)); // true
    console.log(Object.prototype.isPrototypeOf(ken)); // true
    

最佳實務建議

  • 優先使用 ES6+ 原生方法(startsWith、endsWith、trim、padStart 等),僅在舊環境補上 Polyfill。
  • 若必須擴充,建議採用 Object.defineProperty 設定 enumerable: false,避免 for...in 遍歷汙染。
  • 專案中統一管理擴充程式碼於 string.extensions.js,載入順序置於業務邏輯之前。

總結

善用 String.prototype 能大幅提升字串處理的可讀性與復用性,但需謹慎避免汙染全域原型、覆寫內建行為,並在現代環境優先採用標準 API。

copyright © 萬盛學電腦網 all rights reserved