JavaScript中String.prototype用法

來源:互聯網
上載者:User

JavaScript中String.prototype用法

   本文執行個體講述了JavaScript中String.prototype用法。分享給大家供大家參考。具體如下:

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

// 返回字元的長度,一個中文算2個

String.prototype.ChineseLength=function()

{

return this.replace(/[^\x00-\xff]/g,"**").length;

}

// 判斷字串是否以指定的字串結束

String.prototype.EndsWith = function(str)

{

return this.substr(this.length - str.length) == str;

}

// 去掉字元左端的的空白字元

String.prototype.LeftTrim = function()

{

return this.replace(/(^[\\s]*)/g, "");

}

// 去掉字元右端的空白字元

String.prototype.RightTrim = function()

{

return this.replace(/([\\s]*$)/g, "");

}

// 判斷字串是否以指定的字串開始

String.prototype.StartsWith = function(str)

{

return this.substr(0, str.length) == str;

}

// 去掉字元兩端的空白字元

String.prototype.Trim = function()

{

return this.replace(/(^\s*)|(\s*$)/g, "");

}

  這就是我們經常看到的為內部對象, 如 String, Math 等再添加其它屬性和方法的技巧. 對於任何的內部對象和自訂對象, 你都也可以通過 prototype 來重載其下的屬性和方法. 那麼在調用執行時, 它將調用你所定義的方法和屬性. 下面是樣本:

  ?

1

2

3

4

5

6

7

8

9

10

11

12

// 為內部 String 對象添加方法

String.prototype.myMethod = function(){

return "my define method";

}

// 為內部 String 對象重載方法

String.prototype.toString = function(){

return "my define toString method";

}

var myObj = new String("foo");

alert(myObj.myMethod());

alert(myObj);

alert("foo".toString());

  另外需要注意的是, 所有 JavaScript 內部對的 prototype 屬性都是唯讀. 你可以像上面那樣為內部對象的原型添加或重載屬性和方法,但不能更改該內部對象的 prototype 原型. 然而, 自訂對象可以被賦給新的原型. 也就是說, 像下面這樣做是沒有意思的.

  ?

1

2

3

4

5

6

function Employee() {

this.dept = "HR";

this.manager = "John Johnson";

}

String.prototype = new Employee;

var myString = new String("foo");

  上面的程式在運行之後不會報錯, 但顯然, 如果你調用 myString.dept 將會得到一個非定義的值.

  另外, 一個經常使用的是 prototype 下的 isPrototypeOf() 方法, 它主要用來判斷指定對象是否存在於另一個對象的原型鏈中. 文法如下:

  ?

1

object1.prototype.isPrototypeOf(0bject2);

  上面的格式是用來判斷 Object2 是否出現 Object1 的原型鏈中. 樣本如下:

  ?

1

2

3

4

5

6

7

8

9

10

function Person() {

this.name = "Rob Roberson";

this.age = 31;

}

function Employee() {

this.dept = "HR";

this.manager = "John Johnson";

}

Employee.prototype = new Person();

var Ken = new Employee();

  當執行 Employee.prototype.isPrototypeOf(Ken), Person.prototype.isPrototypeOf(Ken) 和 Object.prototype.isPrototypeOf(Ken) 時, 結果都會返回 true.

  希望本文所述對大家的javascript程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.