js如何存儲對象
這是最常用的方式,通過大括號{}來創(chuàng)建個對象,直接為其添加屬性和值。
```javascript
let immigrationLawyer = {
name: 'John Doe',
specialty: 'Investment Immigration'
}
```
這種方式主要用于創(chuàng)建多個具有相同屬性的對象。
```javascript
function Lawyer(name, specialty) {
this.name = name;
this.specialty = specialty;
}
let immigrationLawyer = new Lawyer('John Doe', 'Investment Immigration');
```
JavaScript中的每個對象都有個原型(prototype)通過這個原型為對象添加屬性和方法。
```javascript
function Lawyer() {}
Lawyer.prototype.name = 'John Doe';
Lawyer.prototype.specialty = 'Investment Immigration';
let immigrationLawyer = new Lawyer();
```
這是種更現(xiàn)代的方式來定義對象。
```javascript
class Lawyer {
constructor(name, specialty) {
this.name = name;
this.specialty = specialty;
}
}
let immigrationLawyer = new Lawyer('John Doe', 'Investment Immigration');
```