一、JavaScript 中,萬物皆對象!但對象也是有區別的。分爲普通對象和函數對象。
凡是通過 new Function() 創建的對象都是函數對象,其他的都是普通對象。
Object 、Function 是 JavaScript 自帶的函數對象。
var o1 = {};
var o2 =new Object();
var o3 = new f1();
function f1(){};
var f2 = function(){};
var f3 = new Function('str','console.log(str)');
console.log(typeof Object); //function
console.log(typeof Function); //function
console.log(typeof f1); //function
console.log(typeof f2); //function
console.log(typeof f3); //function
console.log(typeof o1); //object
console.log(typeof o2); //object
console.log(typeof o3); //object
二、構造函數
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.sayName = function() { alert(this.name) }
}
var person1 = new Person('Zaxlct', 28, 'Software Engineer');
var person2 = new Person('Mick', 23, 'Doctor');
person1 和 person2 都是 Person 的實例
這兩個實例都有一個 constructor (構造函數)屬性,該屬性(是一個指針)指向 Person。即:
console.log(person1.constructor == Person); //true
console.log(person2.constructor == Person); //true
我們要記住兩個概念(構造函數,實例):
person1 和 person2 都是 構造函數 Person 的實例
一個公式:
實例的構造函數屬性(constructor)指向構造函數。
person1.constructor == Person
三、原型對象
function Person(){}
每個函數對象都有一個prototype 屬性,即Person.prototype,這個屬性指向函數的原型對象(一個普通對象)。
【公式一】:每個對象都有 proto 屬性,但只有函數對象纔有 prototype 屬性
在大多數情況下,proto可以理解爲"構造器的原型",即:proto === constructor.prototype
原型對象,顧名思義,它就是一個普通對象(廢話 = =!)。從現在開始你要牢牢記住原型對象就是 Person.prototype ,它有一個默認的屬性:constructor(構造函數),這個屬性(是一個指針)指向 prototype 屬性所在的函數(Person)
即:Person.prototype.constructor == Person
【結論】:原型對象(Person.prototype)是 構造函數(Person)的一個實例。