1. 構造函數constructor function
(1). 構造函數是一個常規函數,使用構造函數便於多次創建類似的對象。
- 構造函數的名稱以大寫字母開始。
- 構造函數用new操作符來調用。
如:function Animal (name, age) {
this.name = name;
this.age = age;
};
let cat = new Animal ('cat', 7);
let dog = new Animal ('dog' , 5);
- 如果不用new操作符來調用的話,this.fistName調用的是全局變量,而不是聲明的本地變量。
如:let duck = Animal ('duck', 5);
console.log(duck.name); //報錯Type Error: Cannot read property 'name' of undefined
- 爲了避免報錯,可以强迫用戶在調用時必須使用new關鍵詞,也可以直接返回一個帶有new操作符的對象。
如:强迫用戶必須使用new的。
function Animal (name, age) {
if (!new.target) {
throw Error ('請使用new關鍵詞來調用構造函數');
};
this.name = name;
this.age = age;
};
let cat = Animal ('cat', 7);
console.log(cat.name); // 報錯:'請使用new關鍵詞來調用構造函數'
又如:直接返回新對象的。
function Animal (name, age) {
if (!new.target) {
return new Animal(name, age);
};
this.name = name;
this.age = age;
};
let cat = Animal ('cat', 7);
console.log(cat.name); // 'cat'
2. 原型prototype
(1). Object.prototype有一個重要的屬性,為構造函數,此構造函數引用的是Object()函數。
如:console.log(Object.prototype.constructor === Object); // true
(2). 原型鏈:JavaScript通過 [[Prototype]] 將某對象.prototype鏈接到AObject.prototype對象。
如:function Animal(name,age){
this.name = name;
this.age = age;
};
Animal.prototype.eat = function(food){
return 'Eat ' + food;
}
let cat = new Animal('cat', 7);
console.log(cat.eat('fish')); // 'Eat fish'
console.log(cat.toString()); // [object Object]
console.log(cat.smile()); // TypeError: cat.smile is not a function
在cat對象中并沒有eat()方法,也沒有toString()方法,但JavaScript通過[[Prototype]]將cat與Animal.prototype, Object.prototype相連接,使cat也能調用到屬於Animal與Object的方法。
JavaScript先搜索cat是否有eat和同String方法,沒有發現這兩個方法后,通過[[Prototype]]原型鏈接搜索Animal是否有這兩個方法,發現有則調用此方法,若沒有,就再搜索Object.prototype裏有沒有此方法。同樣,有則調用。但若Object.prototype裏也沒有的話,就會報錯TypeError。
(3). 在JavaScript原型對象中定義方法
如:Animal.prototype.eat = function () {
return "Eat something.";
};
(4). 當在一個對象中定義一個方法時,該方法只對該對象可用,不能與其他對象共享
如:cat.play = function () {
return 'Catch my hand';
};
let dog = new Animal('dog', 9);
console.log(dog.play()); // TypeError: dog.play is not a function
(5). 獲取原型的鏈接 __proto__, 或Object.getPrototypeOf(), 或object.constructor.prototype
如:console.log(cat.__proto__ === Animal.prototype); // true
console.log(cat.__proto__ === dog.__proto__); // true
console.log(cat.__proto__ === Object.getPrototypeOf(cat)); // true
console.log(cat.__proto__ === cat.constructor.prototype); // true