曾經(jīng)有人說 JS 語言中萬物皆對(duì)象
,雖然這種說法不一定完全準(zhǔn)確,但也有一定的道理。原因是 JS 的語法看起來所有的數(shù)據(jù)類型都像是一個(gè)對(duì)象,包括原始類型。
const a = 1.234;
console.log(a.toString());
console.log(a.valueOf());
console.log(a.toFixed(2));
console.log(Number.prototype);
const b = '前端路引';
console.log(b.length);
console.log(b.substring(2));
console.log(b.padEnd(10, '*'));
console.log(String.prototype);
const c = true;
console.log(c.toString());
console.log(Boolean.prototype);
以上展示了 Number、String、Boolean 三種原始類型的方法。a.xxx()
這種寫法就表示 xxx
是 a 的方法。
一般定義在對(duì)象上的 函數(shù)
都稱之為 對(duì)象方法
,使用語法: xxx.yyy()
。對(duì)象除了方法還有 對(duì)象屬性
,使用語法: xxx.yyy
。
方法和屬性的區(qū)別是:方法是函數(shù),屬性是值。
舉個(gè)例子:
const obj = {
name: '前端路引',
age: 1,
sayHi() {
console.log(`我是${this.name},我今年${this.age}歲`);
}
}
以上是一個(gè) JS 的對(duì)象字面量定義方式,除了最常用的對(duì)象字面量,還可以像 Array 一樣,使用構(gòu)造函數(shù)來定義對(duì)象,也可以使用 Class
自定義對(duì)象。
對(duì)象定義
JS 的對(duì)象定義可比 數(shù)組 的花樣多多了,下面來一一展示。
對(duì)象字面量
JS 的對(duì)象值與數(shù)組一樣,無任何限制,可以是任意值,包括函數(shù)、數(shù)組、對(duì)象、undefined、null、NaN 等。
const dynamicKey = 'dynamicKey';
const fnKey = () => {};
const obj1 = {
name: '前端路引',
age: 1,
'favorite-color': 'blue',
[Symbol('id')]: 123,
[dynamicKey]: 'value',
[fnKey]: '使用函數(shù)作為鍵名稱',
greet() {
console.log('Hello!');
},
say: function () {
console.log('Hi!');
}
};
構(gòu)造函數(shù)
雖然此方法使用較少,但這種方式也可以用來定義一個(gè)對(duì)象。以下代碼與上面的對(duì)象字面量定義的對(duì)象一樣:
const dynamicKey = 'dynamicKey';
const fnKey = () => {};
const obj2 = new Object();
obj2.name = '前端路引';
obj2.age = 1;
obj2['favorite-color'] = 'blue';
obj2[Symbol('id')] = 123;
obj2[dynamicKey] = 'value';
obj2[fnKey] = '使用函數(shù)作為鍵名稱';
obj2.greet = function () {
console.log('Hello!');
}
obj2.say = function () {
console.log('Hi!');
}
Object.create()
使用對(duì)象的靜態(tài)方法 Object.create()
來創(chuàng)建對(duì)象。
靜態(tài)方法和對(duì)象原型鏈方法的區(qū)別是:靜態(tài)方法屬于對(duì)象本身,對(duì)象原型鏈上的方法屬于對(duì)象實(shí)例。
看例子:
const obj3 = Object.create({
name: '前端路引',
})
obj3.toString()
Object.create
多用于繼承一個(gè)對(duì)象,擴(kuò)展原有對(duì)象的功能:
const obj4 = {
name: '前端路引',
}
const obj5 = Object.create(obj4);
obj5.age = 1;
obj5['favorite-color'] = 'blue';
自定義構(gòu)造函數(shù)
除了使用 JS 提供的內(nèi)置構(gòu)造函數(shù),還可以自定義構(gòu)造函數(shù)來創(chuàng)建一個(gè)對(duì)象。比如:
function WeChat () {
this.name = '前端路引';
this.age = 1;
this['favorite-color'] = 'blue';
}
const obj6 = new WeChat();
function
關(guān)鍵字可不止用于函數(shù)定義,還能用來自定義構(gòu)造函數(shù),這是在 ES6 出現(xiàn)之前自定義類最常用的方式。
Class
為了消除語法歧義,ES6 引入了 Class
定義類,再通過 new 關(guān)鍵字創(chuàng)建實(shí)例對(duì)象,這種方式完全像是 function 的語法糖。
class WeChat {
constructor() {
this.name = '前端路引';
this.age = 1;
this['favorite-color'] = 'blue';
}
say() {
console.log('Hi!');
}
}
const obj7 = new WeChat();
對(duì)象取值
對(duì)象的取值方法也多得眼花繚亂,下面一一展示。
點(diǎn)語法
常規(guī)屬性可以使用 .
取值,比如:
const obj1 = {
name: '前端路引',
age: 1,
'favorite-color': 'blue',
say() {
console.log('Hi!');
}
}
console.log(obj1.name);
console.log(obj1.say());
方括號(hào)取值
.
語法有個(gè)問題,比如上面對(duì)象中 favorite-color
屬性,如果直接使用 obj1.favorite-color
,會(huì)報(bào)錯(cuò),因?yàn)?nbsp;-
會(huì)被當(dāng)做減號(hào)處理,導(dǎo)致報(bào)錯(cuò) ReferenceError: color is not defined
。
這時(shí)候可以把對(duì)象當(dāng)做數(shù)組來處理,使用方括號(hào) []
取值,比如:
const obj1 = {
name: '前端路引',
age: 1,
'favorite-color': 'blue',
say() {
console.log('Hi!');
}
}
console.log(obj1['favorite-color']);
console.log(obj1['say']());
使用方括號(hào)取值時(shí),如果屬性名是動(dòng)態(tài)的,可以使用變量來取值,比如:
const dynamicKey = 'dynamicKey';
const obj1 = {
[dynamicKey]: '前端路引',
}
console.log(obj1[dynamicKey]);
解構(gòu)賦值
作為 ES6 引入的新特性,此寫法如果不了解,那么代碼可能都看不懂。
const obj1 = {
name: '前端路引',
age: 1,
}
const { name, age, up = '微信公眾號(hào)' } = obj1;
console.log(name, age);
console.log(up);
Object 靜態(tài)方法
Object 自身還提供了一些靜態(tài)方法,用于獲取數(shù)組的鍵值。
const obj1 = {
name: '前端路引',
age: 1,
}
const keys = Object.keys(obj1);
const values = Object.values(obj1);
const entries = Object.entries(obj1);
console.log(keys);
console.log(values);
console.log(entries);
Getter / Setter 方法
使用 get
方法,可以設(shè)置對(duì)象的計(jì)算屬性,用于攔截對(duì)象的取值,比如:
const obj1 = {
firstName: '微信公眾號(hào):',
lastName: '前端路引',
get name() {
return `${this.firstName}:${this.lastName}`;
},
set name(value) {
[this.firstName, this.lastName] = value.split(':');
}
}
console.log(obj1.name);
obj1.name = '前端路引:微信公眾號(hào)';
console.log(obj1.name);
原型鏈訪問
如果取的屬性對(duì)象本身不存在,則會(huì)順著原型鏈查找,直到找到為止,比如:
const obj1 = {
name: '前端路引',
age: 1,
}
console.log(obj1.toString());
可選鏈
ES2020 引入了可選鏈,用于解決對(duì)象取值時(shí),如果屬性不存在,會(huì)報(bào)錯(cuò)的問題,比如:
const obj1 = {
name: '前端路引',
age: 1,
}
console.log(obj1.address.city);
console.log(obj1?.address?.city);
寫在最后
以上已包含絕大多數(shù)應(yīng)用場(chǎng)景,但是也會(huì)有一些不太常用的寫法未包含,比如 Reflect.get(obj, 'a')
。作為入門條件,掌握以上內(nèi)容已經(jīng)完全夠用。
轉(zhuǎn)自https://www.cnblogs.com/linx/p/18903865
該文章在 2025/6/2 9:10:55 編輯過