1、創(chuàng)建一個 Object 實例
1
2
3
4
5
6
7
8
|
var person = new Object(); person.name = "rose" ; person.age = 18; person.job = "actor" ; person.sayName = function () { console.log( this .name); }; console.log(person); |
2、對象字面量
1
2
3
4
5
6
7
8
9
|
var person = { name: "rose" , age: 18, job: "actor" , sayName: function () { console.log( this .name); }, }; console.log(person); |
上面兩種方式是創(chuàng)建對象的兩種基本方式,他們的原型就是 Object
3、工廠模式
1
2
3
4
5
6
7
8
9
10
11
12
|
function createPerson(name,age,actor){ var person = new Object(); person.name = "rose" ; person.age = 18; person.job = "actor" ; person.sayName = function () { console.log( this .name); }; return person } console.log(p1 instanceof Object); //true console.log(p1 instanceof createPerson); //false |
從上面代碼中我們可以看出來,工廠模式實際上就是借助函數(shù),內(nèi)部返回使用第一種方式( new Object())創(chuàng)建的對象。
優(yōu)點:可以很方便的創(chuàng)建相似對象。
缺點:沒有解決對象識別的問題,即怎樣知道一個對象的類型。
4、構(gòu)造函數(shù)方式
1
2
3
4
5
6
7
8
9
10
11
|
function Person(name, age, job) { this .name = name; this .age = age; this .job = job; this .sayName = function () { console.log( this .name); }; } var p = new person( "rose" , 18, "actor" ); console.log(p instanceof Person); //true console.log(p instanceof Object); //true |
構(gòu)造函數(shù)可以創(chuàng)建特定類型的對象,像 Object , Array 這樣的原生構(gòu)造函數(shù),在運行時會自動出現(xiàn)在執(zhí)行環(huán)境中。
構(gòu)造函數(shù)模式與工廠模式的不同之處為:
- 沒有顯式得創(chuàng)建對象,
- 直接將屬性和方法賦值給了this對象
- 沒有return語句
構(gòu)造函數(shù)方式創(chuàng)建對象必須使用 new ,操作符,會經(jīng)歷下面四個步驟
- 創(chuàng)建一個對象
- this指向這個新創(chuàng)建的對象
- 執(zhí)行代碼
- 返回這個對象
構(gòu)造函數(shù)方式的優(yōu)點:以構(gòu)造函數(shù)創(chuàng)建的對象,在其原型上都會有一個 constructor 屬性,這個屬性指向構(gòu)造函數(shù) Person 而這個屬性最初是用來標識數(shù)據(jù)類型的。
憂化
1
2
3
4
5
6
7
8
9
10
|
function Person(name, age, job) { this .name = name; this .age = age; this .job = job; this .sayName = sayName; } function sayName(){ console.log( this .name); } var p = new person( "rose" , 18, "actor" ); |
缺點:當對象需要很多方法的時候,就會定義多個全局作用域下的函數(shù),這樣一來,不僅毫無封裝性可言,而且讓全局作用域下的函數(shù)過多。
5、原型模式
1
2
3
4
5
6
7
8
9
|
function Person() {} Person.prototype.name = "rose" ; Person.prototype.age = 18; Person.prototype.sayName = function () { console.log( this .name); }; var p = new Person(); console.log(p); |
說到原型對象就要說一下原型鏈,原型與原型鏈對象如下圖所示:
我們可以看到,在prototype上面定義的所有屬性都是在其原型對象上。在原型對象上的屬性與方法屬于公有屬性和公有方法。其所有實例都可以訪問到。
6、**組合使用構(gòu)造函數(shù)模式和原型模式 ** 最常用
1
2
3
4
5
6
7
8
9
|
function Person(name, age) { this .name = name; this .age = age; } Person.prototype.sayName = function () { console.log( this .name); }; var p = new Person( "rose" , 18); console.log(p); |
對象在引用其屬性的時候,會按照原型鏈去查找,直到查找到Object的原型。
總結(jié)
到此這篇關(guān)于JS創(chuàng)建自定義對象的六種方法的文章就介紹到這了,更多相關(guān)JS創(chuàng)建自定義對象方法內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://juejin.cn/post/6906311962842365966