學習目標:正則表達式
在 JavaScript 中,全部數據類型均可以視爲對象,固然也能夠自定義對象。
自定義的對象數據類型就是面向對象中的類( Class )的概念。
咱們以一個例子來講明面向過程和麪向對象在程序流程上的不一樣之處。
假設咱們要處理學生的成績表,爲了表示一個學生的成績,面向過程的程序能夠用一個對象表示:數組
var std1 = { name: 'Michael', score: 98 } var std2 = { name: 'Bob', score: 81 }
而處理學生成績能夠經過函數實現,好比打印學生的成績:閉包
function printScore (student) { console.log('姓名:' + student.name + ' ' + '成績:' + student.score) }
若是採用面向對象的程序設計思想,咱們首選思考的不是程序的執行流程,app
而是 Student 這種數據類型應該被視爲一個對象,這個對象擁有 name 和 score 這兩個屬性(Property)。函數
若是要打印一個學生的成績,首先必須建立出這個學生對應的對象,而後,給對象發一個 printScore 消息,讓對象本身把本身的數據打印出來。學習
抽象數據行爲模板(Class):this
function Student (name, score) { this.name = name this.score = score } Student.prototype.printScore = function () { console.log('姓名:' + this.name + ' ' + '成績:' + this.score) }
根據模板建立具體實例對象(Instance):spa
var std1 = new Student('Michael', 98) var std2 = new Student('Bob', 81)
實例對象具備本身的具體行爲(給對象發消息):prototype
std1.printScore() // => 姓名:Michael 成績:98 std2.printScore() // => 姓名:Bob 成績 81
面向對象的設計思想是從天然界中來的,由於在天然界中,類(Class)和實例(Instance)的概念是很天然的。設計
Class 是一種抽象概念,好比咱們定義的 Class——Student ,是指學生這個概念,
而實例(Instance)則是一個個具體的 Student ,好比, Michael 和 Bob 是兩個具體的 Student 。
因此,面向對象的設計思想是:
面向對象的抽象程度又比函數要高,由於一個 Class 既包含數據,又包含操做數據的方法。
咱們能夠直接經過 new Object() 建立:
var person = new Object() person.name = 'Jack' person.age = 18 person.sayName = function () { console.log(this.name) }
var person = { name: 'Jack', age: 18, sayName: function () { console.log(this.name) } }
對於上面的寫法當然沒有問題,可是假如咱們要生成兩個 person 實例對象呢?
咱們能夠寫一個函數,解決代碼重複問題:
function createPerson (name, age) { return { name: name, age: age, sayName: function () { console.log(this.name) } } }
而後生成實例對象:
var p1 = createPerson('Jack', 18) var p2 = createPerson('Mike', 18)
這樣封裝確實爽多了,經過工廠模式咱們解決了建立多個類似對象代碼冗餘的問題,
但卻沒有解決對象識別的問題(即怎樣知道一個對象的類型)。
內容引導:
構造函數和實例對象的關係
構造函數的靜態成員和實例成員
一種更優雅的工廠函數就是下面這樣,構造函數:
function Person (name, age) { this.name = name this.age = age this.sayName = function () { console.log(this.name) } } var p1 = new Person('Jack', 18) p1.sayName() // => Jack var p2 = new Person('Mike', 23) p2.sayName() // => Mike
在上面的示例中,Person() 函數取代了 createPerson() 函數,可是實現效果是同樣的。
這是爲何呢?
咱們注意到,Person() 中的代碼與 createPerson() 有如下幾點不一樣之處:
而要建立 Person 實例,則必須使用 new 操做符。
以這種方式調用構造函數會經歷如下 4 個步驟:
下面是具體的僞代碼:
function Person (name, age) { // 當使用 new 操做符調用 Person() 的時候,實際上這裏會先建立一個對象 // var instance = {} // 而後讓內部的 this 指向 instance 對象 // this = instance // 接下來全部針對 this 的操做實際上操做的就是 instance this.name = name this.age = age this.sayName = function () { console.log(this.name) } // 在函數的結尾處會將 this 返回,也就是 instance // return this }
使用構造函數的好處不只僅在於代碼的簡潔性,更重要的是咱們能夠識別對象的具體類型了。
在每個實例對象中的_proto_中同時有一個 constructor 屬性,該屬性指向建立該實例的構造函數:
console.log(p1.constructor === Person) // => true console.log(p2.constructor === Person) // => true console.log(p1.constructor === p2.constructor) // => true
對象的 constructor 屬性最初是用來標識對象類型的,
可是,若是要檢測對象的類型,仍是使用 instanceof 操做符更可靠一些:
console.log(p1 instanceof Person) // => true console.log(p2 instanceof Person) // => true
使用構造函數帶來的最大的好處就是建立對象更方便了,可是其自己也存在一個浪費內存的問題:
function Person (name, age) { this.name = name this.age = age this.type = 'human' this.sayHello = function () { console.log('hello ' + this.name) } } var p1 = new Person('lpz', 18) var p2 = new Person('Jack', 16)
在該示例中,從表面上好像沒什麼問題,可是實際上這樣作,有一個很大的弊端。那就是對於每個實例對象,type 和 sayHello 都是如出一轍的內容,每一次生成一個實例,都必須爲重複的內容,多佔用一些內存,若是實例對象不少,會形成極大的內存浪費。
console.log(p1.sayHello === p2.sayHello) // => false
對於這種問題咱們能夠把須要共享的函數定義到構造函數外部:
function sayHello = function () { console.log('hello ' + this.name) } function Person (name, age) { this.name = name this.age = age this.type = 'human' this.sayHello = sayHello } var p1 = new Person('lpz', 18) var p2 = new Person('Jack', 16) console.log(p1.sayHello === p2.sayHello) // => true
這樣確實能夠了,可是若是有多個須要共享的函數的話就會形成全局命名空間衝突的問題。
你確定想到了能夠把多個函數放到一個對象中用來避免全局命名空間衝突的問題:
var fns = { sayHello: function () { console.log('hello ' + this.name) }, sayAge: function () { console.log(this.age) } } function Person (name, age) { this.name = name this.age = age this.type = 'human' this.sayHello = fns.sayHello this.sayAge = fns.sayAge } var p1 = new Person('lpz', 18) var p2 = new Person('Jack', 16) console.log(p1.sayHello === p2.sayHello) // => true console.log(p1.sayAge === p2.sayAge) // => true
至此,咱們利用本身的方式基本上解決了構造函數的內存浪費問題。
小結
構造函數和實例對象的關係
內容引導:
原生對象的原型
Javascript 規定,每個構造函數都有一個 prototype 屬性,指向另外一個對象。
這個對象的全部屬性和方法,都會被構造函數的實例繼承。
這也就意味着,咱們能夠把全部對象實例須要共享的屬性和方法直接定義在 prototype 對象上。
function Person (name, age) { this.name = name this.age = age } console.log(Person.prototype) Person.prototype.type = 'human' Person.prototype.sayName = function () { console.log(this.name) } var p1 = new Person(...) var p2 = new Person(...) console.log(p1.sayName === p2.sayName) // => true
這時全部實例的 type 屬性和 sayName() 方法,
其實都是同一個內存地址,指向 prototype 對象,所以就提升了運行效率。
任何函數都具備一個 prototype 屬性,該屬性是一個對象。
function F () {} console.log(F.prototype) // => object F.prototype.sayHi = function () { console.log('hi!') }
構造函數的 prototype 對象默認都有一個 constructor 屬性,指向 prototype 對象所在函數。
console.log(F.constructor === F) // => true
經過構造函數獲得的實例對象內部會包含一個指向構造函數的 prototype 對象的指針 __proto__。
var instance = new F() console.log(instance.__proto__ === F.prototype) // => true
<p class="tip">
proto 是非標準屬性。
</p>
實例對象能夠直接訪問原型對象成員。
instance.sayHi() // => hi!
總結:
瞭解了 構造函數-實例-原型對象 三者之間的關係後,接下來咱們來解釋一下爲何實例對象能夠訪問原型對象中的成員。
每當代碼讀取某個對象的某個屬性時,都會執行一次搜索,目標是具備給定名字的屬性
也就是說,在咱們調用 person1.sayName() 的時候,會前後執行兩次搜索:
而這正是多個對象實例共享原型所保存的屬性和方法的基本原理。
總結:
咱們注意到,前面例子中每添加一個屬性和方法就要敲一遍 Person.prototype 。
爲減小沒必要要的輸入,更常見的作法是用一個包含全部屬性和方法的對象字面量來重寫整個原型對象:
function Person (name, age) { this.name = name this.age = age } Person.prototype = { type: 'human', sayHello: function () { console.log('我叫' + this.name + ',我今年' + this.age + '歲了') } }
在該示例中,咱們將 Person.prototype 重置到了一個新的對象。
這樣作的好處就是爲 Person.prototype 添加成員簡單了,可是也會帶來一個問題,那就是原型對象丟失了 constructor 成員。
因此,咱們爲了保持 constructor 的指向正確,建議的寫法是:
function Person (name, age) { this.name = name this.age = age } Person.prototype = { constructor: Person, // => 手動將 constructor 指向正確的構造函數 type: 'human', sayHello: function () { console.log('我叫' + this.name + ',我今年' + this.age + '歲了') } }
<p class="tip">
全部函數都有 prototype 屬性對象。
</p>
練習:爲數組對象和字符串對象擴展原型方法
function Person (name, age) { this.type = 'human' this.name = name this.age = age } function Student (name, age) { // 借用構造函數繼承屬性成員 Person.call(this, name, age) } var s1 = Student('張三', 18) console.log(s1.type, s1.name, s1.age) // => human 張三 18
function Person (name, age) { this.type = 'human' this.name = name this.age = age } Person.prototype.sayName = function () { console.log('hello ' + this.name) } function Student (name, age) { Person.call(this, name, age) } // 原型對象拷貝繼承原型對象成員 for(var key in Person.prototype) { Student.prototype[key] = Person.prototype[key] } var s1 = Student('張三', 18) s1.sayName() // => hello 張三
function Person (name, age) { this.type = 'human' this.name = name this.age = age } Person.prototype.sayName = function () { console.log('hello ' + this.name) } function Student (name, age) { Person.call(this, name, age) } // 利用原型的特性實現繼承 Student.prototype = new Person() var s1 = Student('張三', 18) console.log(s1.type) // => human s1.sayName() // => hello 張三
函數的調用方式決定了 this 指向的不一樣:
這就是對函數內部 this 指向的基本整理,寫代碼寫多了天然而然就熟悉了。
函數也是對象
call、apply、bind
那瞭解了函數 this 指向的不一樣場景以後,咱們知道有些狀況下咱們爲了使用某種特定環境的 this 引用,
這時候時候咱們就須要採用一些特殊手段來處理了,例如咱們常常在定時器外部備份 this 引用,而後在定時器函數內部使用外部 this 的引用。
然而實際上對於這種作法咱們的 JavaScript 爲咱們專門提供了一些函數方法用來幫咱們更優雅的處理函數內部 this 指向問題。
這就是接下來咱們要學習的 call、apply、bind 三個函數方法。
call
call() 方法調用一個函數, 其具備一個指定的 this 值和分別地提供的參數(參數的列表)。
<p class="danger">
注意:該方法的做用和 apply() 方法相似,只有一個區別,就是 call() 方法接受的是若干個參數的列表,而 apply() 方法接受的是一個包含多個參數的數組。
</p>
語法:
fun.call(thisArg[, arg1[, arg2[, ...]]])
參數:
thisArg
arg1, arg2, ...
apply
apply() 方法調用一個函數, 其具備一個指定的 this 值,以及做爲一個數組(或相似數組的對象)提供的參數。
<p class="danger">
注意:該方法的做用和 call() 方法相似,只有一個區別,就是 call() 方法接受的是若干個參數的列表,而 apply() 方法接受的是一個包含多個參數的數組。
</p>
語法:
fun.apply(thisArg, [argsArray])
參數:
apply() 與 call() 很是類似,不一樣之處在於提供參數的方式。
apply() 使用參數數組而不是一組參數列表。例如:
fun.apply(this, ['eat', 'bananas'])
bind
bind() 函數會建立一個新函數(稱爲綁定函數),新函數與被調函數(綁定函數的目標函數)具備相同的函數體(在 ECMAScript 5 規範中內置的call屬性)。
當目標函數被調用時 this 值綁定到 bind() 的第一個參數,該參數不能被重寫。綁定函數被調用時,bind() 也接受預設的參數提供給原函數。
一個綁定函數也能使用new操做符建立對象:這種行爲就像把原函數當成構造器。提供的 this 值被忽略,同時調用時的參數被提供給模擬函數。
語法:
fun.bind(thisArg[, arg1[, arg2[, ...]]])
參數:
thisArg
arg1, arg2, ...
返回值:
返回由指定的this值和初始化參數改造的原函數拷貝。
小結
call 和 apply 特性同樣
bind
bind 支持傳遞參數,它的傳參方式比較特殊,一共有兩個位置能夠傳遞
arguments
caller
length
name
function fn(x, y, z) { console.log(fn.length) // => 形參的個數 console.log(arguments) // 僞數組實參參數集合 console.log(arguments.callee === fn) // 函數自己 console.log(fn.caller) // 函數的調用者 console.log(fn.name) // => 函數的名字 } function f() { fn(10, 20, 30) } f()
閉包就是可以讀取其餘函數內部變量的函數,
因爲在 Javascript 語言中,只有函數內部的子函數才能讀取局部變量,
所以能夠把閉包簡單理解成 「定義在一個函數內部的函數」。
因此,在本質上,閉包就是將函數內部和函數外部鏈接起來的一座橋樑。
閉包的用途:
一些關於閉包的例子
示例1:
var arr = [10, 20, 30] for(var i = 0; i < arr.length; i++) { arr[i] = function () { console.log(i) } }
示例2:
console.log(111) for(var i = 0; i < 3; i++) { setTimeout(function () { console.log(i) }, 0) } console.log(222)
正則表達式是對字符串操做的一種邏輯公式,就是用事先定義好的一些特定字符、及這些特定字符的組合,組成一個「規則字符串」,這個「規則字符串」用來表達對字符串的一種過濾邏輯。
方式1:
var reg = new Regex('\d', 'i'); var reg = new Regex('\d', 'gi');
方式2:
var reg = /\d/i; var reg = /\d/gi;
// 1. 提取工資 var str = "張三:1000,李四:5000,王五:8000。"; var array = str.match(/\d+/g); console.log(array); // 2. 提取email地址 var str = "123123@xx.com,fangfang@valuedopinions.cn 286669312@qq.com 二、emailenglish@emailenglish.englishtown.com 286669312@qq.com..."; var array = str.match(/\w+@\w+\.\w+(\.\w+)?/g); console.log(array); // 3. 分組提取 // 3. 提取日期中的年部分 2015-5-10var dateStr = '2016-1-5'; // 正則表達式中的()做爲分組來使用,獲取分組匹配到的結果用Regex.$1 $2 $3....來獲取 var reg = /(\d{4})-\d{1,2}-\d{1,2}/; if (reg.test(dateStr)) { console.log(RegExp.$1);} // 4. 提取郵件中的每一部分 var reg = /(\w+)@(\w+)\.(\w+)(\.\w+)?/; var str = "123123@xx.com"; if (reg.test(str)) { console.log(RegExp.$1); console.log(RegExp.$2); console.log(RegExp.$3);}
// 1. 替換全部空白 var str = " 123AD asadf asadfasf adf "; str = str.replace(/\s/g,"xx"); console.log(str); // 2. 替換全部,|, var str = "abc,efg,123,abc,123,a"; str = str.replace(/,|,/g, "."); console.log(str);
QQ號:<input type="text" id="txtQQ"><span></span><br> 郵箱:<input type="text" id="txtEMail"><span></span><br> 手機:<input type="text" id="txtPhone"><span></span><br> 生日:<input type="text" id="txtBirthday"><span></span><br> 姓名:<input type="text" id="txtName"><span></span><br>
//獲取文本框 var txtQQ = document.getElementById("txtQQ"); var txtEMail = document.getElementById("txtEMail"); var txtPhone = document.getElementById("txtPhone"); var txtBirthday = document.getElementById("txtBirthday"); var txtName = document.getElementById("txtName"); // txtQQ.onblur = function () { //獲取當前文本框對應的span var span = this.nextElementSibling; var reg = /^\d{5,12}$/; //判斷驗證是否成功 if(!reg.test(this.value) ){ //驗證不成功 span.innerText = "請輸入正確的QQ號"; span.style.color = "red"; }else{ //驗證成功 span.innerText = ""; span.style.color = ""; } }; //txtEMail txtEMail.onblur = function () { //獲取當前文本框對應的span var span = this.nextElementSibling; var reg = /^\w+@\w+\.\w+(\.\w+)?$/; //判斷驗證是否成功 if(!reg.test(this.value) ){ //驗證不成功 span.innerText = "請輸入正確的EMail地址"; span.style.color = "red"; }else{ //驗證成功 span.innerText = ""; span.style.color = ""; } };
表單驗證部分,封裝成函數:
var regBirthday = /^\d{4}-\d{1,2}-\d{1,2}$/; addCheck(txtBirthday, regBirthday, "請輸入正確的出生日期"); //給文本框添加驗證 function addCheck(element, reg, tip) { element.onblur = function () { //獲取當前文本框對應的span var span = this.nextElementSibling; //判斷驗證是否成功 if(!reg.test(this.value) ){ //驗證不成功 span.innerText = tip; span.style.color = "red"; }else{ //驗證成功 span.innerText = ""; span.style.color = ""; } }; }
經過給元素增長自定義驗證屬性對錶單進行驗證:
<form id="frm"> QQ號:<input type="text" name="txtQQ" data-rule="qq"><span></span><br> 郵箱:<input type="text" name="txtEMail" data-rule="email"><span></span><br> 手機:<input type="text" name="txtPhone" data-rule="phone"><span></span><br> 生日:<input type="text" name="txtBirthday" data-rule="date"><span></span><br> 姓名:<input type="text" name="txtName" data-rule="cn"><span></span><br> </form>
// 全部的驗證規則 var rules = [ { name: 'qq', reg: /^\d{5,12}$/, tip: "請輸入正確的QQ" }, { name: 'email', reg: /^\w+@\w+\.\w+(\.\w+)?$/, tip: "請輸入正確的郵箱地址" }, { name: 'phone', reg: /^\d{11}$/, tip: "請輸入正確的手機號碼" }, { name: 'date', reg: /^\d{4}-\d{1,2}-\d{1,2}$/, tip: "請輸入正確的出生日期" }, { name: 'cn', reg: /^[\u4e00-\u9fa5]{2,4}$/, tip: "請輸入正確的姓名" }]; addCheck('frm'); //給文本框添加驗證 function addCheck(formId) { var i = 0, len = 0, frm =document.getElementById(formId); len = frm.children.length; for (; i < len; i++) { var element = frm.children[i]; // 表單元素中有name屬性的元素添加驗證 if (element.name) { element.onblur = function () { // 使用dataset獲取data-自定義屬性的值 var ruleName = this.dataset.rule; var rule =getRuleByRuleName(rules, ruleName); var span = this.nextElementSibling; //判斷驗證是否成功 if(!rule.reg.test(this.value) ){ //驗證不成功 span.innerText = rule.tip; span.style.color = "red"; }else{ //驗證成功 span.innerText = ""; span.style.color = ""; } } } } } // 根據規則的名稱獲取規則對象 function getRuleByRuleName(rules, ruleName) { var i = 0, len = rules.length; var rule = null; for (; i < len; i++) { if (rules[i].name == ruleName) { rule = rules[i]; break; } } return rule; }