你可以使用{...}
直接創建對象
也可以通過Function
關鍵詞構造的函數來創建對象。
本篇內容所指的函數,均已將箭頭函數排除在外。因為箭頭函數不能用來構造函數。箭頭函數沒有綁定
this,arguments,super,new.target
。
- 使用
new
關鍵字來調用一個函數,就是使用構造函數創建對象了。如果不使用new
關鍵字,那就是一個普通的函數; - 一般構造函數名使用大寫;
定義一個構造函數
function Student(name) {
this.name = name;
this.hello = function () {
alert('Hello, ' + this.name + '!');
}
}
長的跟普通函數一樣,不使用new
關鍵詞調用,就是普通函數,使用new
關鍵詞調用就是構造函數了。
使用new
關鍵字調用函數,它綁定的this
指向新創建的對象,并默認返回this
,也就是說 不需要再構造函數最后寫 return this
使用構造函數創建對象
var xiaoming = new Student('小明');
xiaoming.name; // '小明'
xiaoming.hello(); // Hello, 小明!
JavaScript創建的每一個對象都會設置一個原型,指向它的原型對象
當我們使用
obj.xxx
訪問對象屬性時,JavaScript引擎現在當前對象上查找該屬性,如果沒有找到,就在其原型對象上找,如果沒有找到就一直上溯到Object.prototype
對象,最后,如果還沒有找到,就只能返回undefined。
例如創建一個數組 var a = [1,2,3];
它的原型鏈如下
a -> Array.prototype -> Object.prototype -> null
因為在Array.Prototype上定義了push方法,所以在可以使用 a.push()
在這里 xiaoming 的原型鏈就是:
xiaoming -> Student.prototype -> Object.prototype -> null
但是xiaoming
可沒有prototype屬性,不過可以用__proto__
非標準語法查看,
Student.prototype
指向的就是xiaoming
的原型對象,默認是個Student
類型的空對象,這個原型對象還有一個屬性constructor
指向Student
函數本身
Student.prototype
中屬性 constructor
也就可以使用了 比如xiaoming
也就擁有了 constructor
屬性,其實就是Student.prototype.constructor
也就是 Student
函數本身。
因此 xiaoming.constructor === Student.prototype.constructor === Student
如果我們通過new Student()
創建了很多對象,這些對象的hello
函數實際上只需要共享同一個函數就可以了,這樣可以節省很多內存。
根據對象的屬性查找原則,我們只要把hello
函數移動到 這些對象的共同的原型上就可以了。
function Student(name) {
this.name = name;
}
Student.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
};
而如果你直接給prototype
賦值,那么就會一不小心改變 Student 的原型 比如:
Student.prototype = {
hello: function () {
alert('Hello, ' + this.name + '!');
},
play:function(){
alert('play with me');
}
}
上面的代碼是賦值操作,而不是在原來的prototype對上增加屬性值,
原來的 Student.prototype
對象是 Student 類型的 {}
其打印結果是 Student {}
它的constructor 是Student函數本身
而直接賦值的這個 {...}
默認是 Object
類型的對象,這個Object對象的 prototype.constructor
也就是自然指向了它的構造函數 [Function: Object]
所以,使用Student
創建對象所繼承的constructor
屬性 就不再是原來的 Student
函數 而是 Object
函數。
如果想讓constructor
依然指向Student
修改原型對象的constructor
的屬性就可以了。
解決方案就是在設置完prototype
之后,設置下constructor
Student.prototype = {
hello: function () {
alert('Hello, ' + this.name + '!');
},
play:function(){
alert('play with me');
}
};
Student.prototype.constructor = Student;
盡管可以這樣解決,你也發現了,Student.prototype的打印結果已經不是Student(Student {}
)的類型了,而是默認對象Object 的類型,然后又更改constructor(Student.prototype.constructor),不覺得有不一致的地方嗎?一個Student類型的原型指向了一個Object類型的對象,其constructor卻是Student函數。
所以我不推薦使用這種方法 給原型對象 增加 屬性或者方法。雖然沒有改變原型鏈,但是改變了原型的指向,稍不注意可能會有一些意外的問題發生。
我依然推崇直接在原來的原型對象上修改:
function Student(name) {
this.name = name;
}
Student.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
};