假如不知道prototype的同學(xué),自行學(xué)習prototype的作用
【prototype 繼承
所有的 JavaScript 對象都會從一個 prototype(原型對象)中繼承屬性和方法:
Date?對象從?Date.prototype?繼承。
Array?對象從?Array.prototype?繼承。
Person?對象從?Person.prototype?繼承。
所有 JavaScript 中的對象都是位于原型鏈頂端的 Object 的實例。
JavaScript 對象有一個指向一個原型對象的鏈。當試圖訪問一個對象的屬性時,它不僅僅在該對象上搜尋,還會搜尋該對象的原型,以及該對象的原型的原型,依次層層向上搜索,直到找到一個名字匹配的屬性或到達原型鏈的末尾。
Date?對象,?Array?對象, 以及?Person?對象從?Object.prototype?繼承。
添加屬性和方法
有的時候我們想要在所有已經(jīng)存在的對象添加新的屬性或方法。
另外,有時候我們想要在對象的構(gòu)造函數(shù)中添加屬性或方法。
使用 prototype 屬性就可以給對象的構(gòu)造函數(shù)添加新的屬性:
function Person(first, last, age, eyecolor) {
?this.firstName = first; ?this.lastName = last; ?this.age = age; ?this.eyeColor = eyecolor;}
Person.prototype.nationality = "English";
當然我們也可以使用 prototype 屬性就可以給對象的構(gòu)造函數(shù)添加新的方法:
function Person(first, last, age, eyecolor) {
?this.firstName = first; ?this.lastName = last; ?this.age = age; ?this.eyeColor = eyecolor;}
Person.prototype.name = function() {
?return this.firstName + " " + this.lastName;};
】
if (!String.prototype.startsWith) {
? ? String.prototype.startsWith = function (searchString, position) {
? ? ? ? position = position || 0;
? ? ? ? //查找的字符串的最后一個匹配是否等于0,假如是,就是以該字符串開頭,否則則不是
? ? ? ? return this.lastIndexOf(searchString, position) === position;
? ? };
}
//eg: hello world .endwith(world);
if (!String.prototype.endsWith) {
? ? String.prototype.endsWith = function (searchString, position) {
? ? ? ? //當位置參數(shù)為undefined的時候 或者位置大于字符串的長度,默認為最后一個字符的位置
? ? ? ? if (typeof position === 'undefined' || position > this.length) {
? ? ? ? ? ? position = this.length;
? ? ? ? }
? ? ? ? //更新position位置,傳入位置減去要查找字符串的長度;
? ? ? ? position -= searchString.length;
? ? ? ? //indexOf() 方法可返回某個指定的字符串值在字符串中首次出現(xiàn)的位置。如果沒有找到匹配的字符串則返回 -1。
? ? ? ? /* 語法
? ? ? ? string.indexOf(searchvalue,start)
? ? ? ? 參數(shù)值
? ? ? ? 參數(shù) 描述
? ? ? ? searchvalue 必需。規(guī)定需檢索的字符串值。
? ? ? ? start 可選的整數(shù)參數(shù)。規(guī)定在字符串中開始檢索的位置。它的合法取值是 0 到 string Object.length - 1。如省略該參數(shù),則將從字符串的首字符開始檢索。*/
? ? ? ? //判斷要查找的字符串開始的位置
? ? ? ? var lastIndex = this.indexOf(searchString, position);
? ? ? ? //查找的字符串等于總長度減去查找字符串的長度,是則返回true,否則 false
? ? ? ? return lastIndex !== -1 && lastIndex === position;
? ? };
}
if (!String.prototype.trimLeft) {
? ? //通過正則替換,把左側(cè)空格干掉;
? ? /*?
? ? 正則里面 \s 指的是 --匹配任何空白字符,包括空格、制表符、換頁符等等。,
? ? 匹配任何空白字符,包括空格、制表符、換頁符等等。
? ? 加號匹配任何空白字符,包括空格、制表符、換頁符等等。*/
? ? String.prototype.trimLeft = function () {
? ? ? ? return this.replace(/^\s+/, '');
? ? };
}