Hướng dẫn is javascript reference based? - là dựa trên tham chiếu javascript?

  • " Trước
  • Tiếp theo "

JavaScript được thiết kế trên một mô hình dựa trên đối tượng đơn giản. Một đối tượng là một tập hợp các thuộc tính và một thuộc tính là một liên kết giữa một tên (hoặc khóa) và một giá trị. Giá trị của một thuộc tính có thể là một hàm, trong trường hợp thuộc tính được gọi là phương thức. Ngoài các đối tượng được xác định trước trong trình duyệt, bạn có thể xác định các đối tượng của riêng mình. Chương này mô tả cách sử dụng các đối tượng, thuộc tính, chức năng và phương thức và cách tạo các đối tượng của riêng bạn.

Tổng quan đối tượng

Các đối tượng trong JavaScript, giống như trong nhiều ngôn ngữ lập trình khác, có thể được so sánh với các đối tượng trong cuộc sống thực. Khái niệm về các đối tượng trong JavaScript có thể được hiểu với cuộc sống thực, các đối tượng hữu hình.

Trong JavaScript, một đối tượng là một thực thể độc lập, với các thuộc tính và loại. So sánh nó với một cốc, ví dụ. Một cốc là một đối tượng, với các thuộc tính. Một cốc có màu, thiết kế, trọng lượng, một vật liệu được làm bằng, v.v ... Theo cùng một cách, các đối tượng JavaScript có thể có các thuộc tính, xác định các đặc điểm của chúng.

Đối tượng và thuộc tính

Một đối tượng JavaScript có các thuộc tính liên quan đến nó. Một thuộc tính của một đối tượng có thể được giải thích là một biến được gắn vào đối tượng. Các thuộc tính đối tượng về cơ bản giống như các biến JavaScript thông thường, ngoại trừ phần đính kèm với các đối tượng. Các thuộc tính của một đối tượng xác định các đặc điểm của đối tượng. Bạn truy cập các thuộc tính của một đối tượng với một ghi chú dấu chấm đơn giản:

Giống như tất cả các biến JavaScript, cả tên đối tượng (có thể là biến bình thường) và tên thuộc tính đều nhạy cảm. Bạn có thể xác định một thuộc tính bằng cách gán nó một giá trị. Ví dụ: chúng ta hãy tạo một đối tượng có tên

myCar['make'] = 'Ford';
myCar['model'] = 'Mustang';
myCar['year'] = 1969;
5 và cung cấp cho nó các thuộc tính có tên
myCar['make'] = 'Ford';
myCar['model'] = 'Mustang';
myCar['year'] = 1969;
6,
myCar['make'] = 'Ford';
myCar['model'] = 'Mustang';
myCar['year'] = 1969;
7 và
myCar['make'] = 'Ford';
myCar['model'] = 'Mustang';
myCar['year'] = 1969;
8 như sau:

const myCar = new Object();
myCar.make = 'Ford';
myCar.model = 'Mustang';
myCar.year = 1969;

Ví dụ trên cũng có thể được viết bằng trình khởi tạo đối tượng, là danh sách được phân phối bằng dấu phẩy bằng 0 hoặc nhiều cặp tên thuộc tính và các giá trị liên quan của một đối tượng, được đặt trong niềng răng xoăn (

myCar['make'] = 'Ford';
myCar['model'] = 'Mustang';
myCar['year'] = 1969;
9):object initializer, which is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces (
myCar['make'] = 'Ford';
myCar['model'] = 'Mustang';
myCar['year'] = 1969;
9):

const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};

Các thuộc tính không được chỉ định của một đối tượng là

// four variables are created and assigned in a single go,
// separated by commas
const myObj = {},
      str = 'myString',
      rand = Math.random(),
      anotherObj = {};

// Now, creating additional properties.
myObj.type              = 'Dot syntax for a key named type';
myObj['date created']   = 'This key has a space';
myObj[str]              = 'This key is in variable str';
myObj[rand]             = 'A random number is the key here';
myObj[anotherObj]       = 'This key is object anotherObj';
myObj['']               = 'This key is an empty string';

console.log(myObj);
console.log(myObj.myString);

/*
[Log] Object
    : "This key is an empty string"
    0.8916485437228595: "A random number is the key here"
    [object Object]: "This key is object anotherObj"
    date created: "This key has a space"
    myString: "This key is in variable str"
    type: "Dot syntax for a key named type"
*/
// notice that in the log, the order of the properties listed is not the same as the order they were created.

// [Log] This key is in variable str
0 (và không phải
// four variables are created and assigned in a single go,
// separated by commas
const myObj = {},
      str = 'myString',
      rand = Math.random(),
      anotherObj = {};

// Now, creating additional properties.
myObj.type              = 'Dot syntax for a key named type';
myObj['date created']   = 'This key has a space';
myObj[str]              = 'This key is in variable str';
myObj[rand]             = 'A random number is the key here';
myObj[anotherObj]       = 'This key is object anotherObj';
myObj['']               = 'This key is an empty string';

console.log(myObj);
console.log(myObj.myString);

/*
[Log] Object
    : "This key is an empty string"
    0.8916485437228595: "A random number is the key here"
    [object Object]: "This key is object anotherObj"
    date created: "This key has a space"
    myString: "This key is in variable str"
    type: "Dot syntax for a key named type"
*/
// notice that in the log, the order of the properties listed is not the same as the order they were created.

// [Log] This key is in variable str
1).

myCar.color; // undefined

Thuộc tính của các đối tượng JavaScript cũng có thể được truy cập hoặc đặt bằng ký hiệu khung (để biết thêm chi tiết, hãy xem Trình truy cập thuộc tính). Các đối tượng đôi khi được gọi là mảng liên kết, vì mỗi thuộc tính được liên kết với giá trị chuỗi có thể được sử dụng để truy cập nó. Vì vậy, ví dụ, bạn có thể truy cập các thuộc tính của đối tượng

myCar['make'] = 'Ford';
myCar['model'] = 'Mustang';
myCar['year'] = 1969;
5 như sau:

myCar['make'] = 'Ford';
myCar['model'] = 'Mustang';
myCar['year'] = 1969;

Tên thuộc tính đối tượng có thể là bất kỳ chuỗi JavaScript hợp lệ nào hoặc bất cứ thứ gì có thể được chuyển đổi thành một chuỗi, bao gồm một chuỗi trống. Tuy nhiên, bất kỳ tên thuộc tính nào không phải là định danh JavaScript hợp lệ đều không thể sử dụng ký hiệu DOT. Ví dụ: tên thuộc tính có không gian hoặc dấu gạch nối, bắt đầu bằng một số hoặc được giữ bên trong một biến chỉ có thể được truy cập bằng ký hiệu khung vuông. Ký hiệu này cũng rất hữu ích khi tên thuộc tính được xác định động, tức là không thể xác định cho đến khi chạy. Ví dụ như sau:

// four variables are created and assigned in a single go,
// separated by commas
const myObj = {},
      str = 'myString',
      rand = Math.random(),
      anotherObj = {};

// Now, creating additional properties.
myObj.type              = 'Dot syntax for a key named type';
myObj['date created']   = 'This key has a space';
myObj[str]              = 'This key is in variable str';
myObj[rand]             = 'A random number is the key here';
myObj[anotherObj]       = 'This key is object anotherObj';
myObj['']               = 'This key is an empty string';

console.log(myObj);
console.log(myObj.myString);

/*
[Log] Object
    : "This key is an empty string"
    0.8916485437228595: "A random number is the key here"
    [object Object]: "This key is object anotherObj"
    date created: "This key has a space"
    myString: "This key is in variable str"
    type: "Dot syntax for a key named type"
*/
// notice that in the log, the order of the properties listed is not the same as the order they were created.

// [Log] This key is in variable str

Tên thuộc tính đối tượng JavaScript (khóa) chỉ có thể là các chuỗi hoặc ký hiệu - tất cả các khóa trong ký hiệu khung vuông được chuyển đổi thành chuỗi trừ khi chúng là ký hiệu. Ví dụ: trong mã trên, khi khóa

// four variables are created and assigned in a single go,
// separated by commas
const myObj = {},
      str = 'myString',
      rand = Math.random(),
      anotherObj = {};

// Now, creating additional properties.
myObj.type              = 'Dot syntax for a key named type';
myObj['date created']   = 'This key has a space';
myObj[str]              = 'This key is in variable str';
myObj[rand]             = 'A random number is the key here';
myObj[anotherObj]       = 'This key is object anotherObj';
myObj['']               = 'This key is an empty string';

console.log(myObj);
console.log(myObj.myString);

/*
[Log] Object
    : "This key is an empty string"
    0.8916485437228595: "A random number is the key here"
    [object Object]: "This key is object anotherObj"
    date created: "This key has a space"
    myString: "This key is in variable str"
    type: "Dot syntax for a key named type"
*/
// notice that in the log, the order of the properties listed is not the same as the order they were created.

// [Log] This key is in variable str
3 được thêm vào
// four variables are created and assigned in a single go,
// separated by commas
const myObj = {},
      str = 'myString',
      rand = Math.random(),
      anotherObj = {};

// Now, creating additional properties.
myObj.type              = 'Dot syntax for a key named type';
myObj['date created']   = 'This key has a space';
myObj[str]              = 'This key is in variable str';
myObj[rand]             = 'A random number is the key here';
myObj[anotherObj]       = 'This key is object anotherObj';
myObj['']               = 'This key is an empty string';

console.log(myObj);
console.log(myObj.myString);

/*
[Log] Object
    : "This key is an empty string"
    0.8916485437228595: "A random number is the key here"
    [object Object]: "This key is object anotherObj"
    date created: "This key has a space"
    myString: "This key is in variable str"
    type: "Dot syntax for a key named type"
*/
// notice that in the log, the order of the properties listed is not the same as the order they were created.

// [Log] This key is in variable str
4, JavaScript sẽ gọi phương thức
// four variables are created and assigned in a single go,
// separated by commas
const myObj = {},
      str = 'myString',
      rand = Math.random(),
      anotherObj = {};

// Now, creating additional properties.
myObj.type              = 'Dot syntax for a key named type';
myObj['date created']   = 'This key has a space';
myObj[str]              = 'This key is in variable str';
myObj[rand]             = 'A random number is the key here';
myObj[anotherObj]       = 'This key is object anotherObj';
myObj['']               = 'This key is an empty string';

console.log(myObj);
console.log(myObj.myString);

/*
[Log] Object
    : "This key is an empty string"
    0.8916485437228595: "A random number is the key here"
    [object Object]: "This key is object anotherObj"
    date created: "This key has a space"
    myString: "This key is in variable str"
    type: "Dot syntax for a key named type"
*/
// notice that in the log, the order of the properties listed is not the same as the order they were created.

// [Log] This key is in variable str
5 của
// four variables are created and assigned in a single go,
// separated by commas
const myObj = {},
      str = 'myString',
      rand = Math.random(),
      anotherObj = {};

// Now, creating additional properties.
myObj.type              = 'Dot syntax for a key named type';
myObj['date created']   = 'This key has a space';
myObj[str]              = 'This key is in variable str';
myObj[rand]             = 'A random number is the key here';
myObj[anotherObj]       = 'This key is object anotherObj';
myObj['']               = 'This key is an empty string';

console.log(myObj);
console.log(myObj.myString);

/*
[Log] Object
    : "This key is an empty string"
    0.8916485437228595: "A random number is the key here"
    [object Object]: "This key is object anotherObj"
    date created: "This key has a space"
    myString: "This key is in variable str"
    type: "Dot syntax for a key named type"
*/
// notice that in the log, the order of the properties listed is not the same as the order they were created.

// [Log] This key is in variable str
3 và sử dụng chuỗi kết quả làm khóa mới.

Bạn cũng có thể truy cập các thuộc tính với giá trị chuỗi được lưu trữ trong một biến. Biến phải được truyền trong ký hiệu khung. Trong ví dụ trên, biến

// four variables are created and assigned in a single go,
// separated by commas
const myObj = {},
      str = 'myString',
      rand = Math.random(),
      anotherObj = {};

// Now, creating additional properties.
myObj.type              = 'Dot syntax for a key named type';
myObj['date created']   = 'This key has a space';
myObj[str]              = 'This key is in variable str';
myObj[rand]             = 'A random number is the key here';
myObj[anotherObj]       = 'This key is object anotherObj';
myObj['']               = 'This key is an empty string';

console.log(myObj);
console.log(myObj.myString);

/*
[Log] Object
    : "This key is an empty string"
    0.8916485437228595: "A random number is the key here"
    [object Object]: "This key is object anotherObj"
    date created: "This key has a space"
    myString: "This key is in variable str"
    type: "Dot syntax for a key named type"
*/
// notice that in the log, the order of the properties listed is not the same as the order they were created.

// [Log] This key is in variable str
7 đã giữ
// four variables are created and assigned in a single go,
// separated by commas
const myObj = {},
      str = 'myString',
      rand = Math.random(),
      anotherObj = {};

// Now, creating additional properties.
myObj.type              = 'Dot syntax for a key named type';
myObj['date created']   = 'This key has a space';
myObj[str]              = 'This key is in variable str';
myObj[rand]             = 'A random number is the key here';
myObj[anotherObj]       = 'This key is object anotherObj';
myObj['']               = 'This key is an empty string';

console.log(myObj);
console.log(myObj.myString);

/*
[Log] Object
    : "This key is an empty string"
    0.8916485437228595: "A random number is the key here"
    [object Object]: "This key is object anotherObj"
    date created: "This key has a space"
    myString: "This key is in variable str"
    type: "Dot syntax for a key named type"
*/
// notice that in the log, the order of the properties listed is not the same as the order they were created.

// [Log] This key is in variable str
8 và đó là
// four variables are created and assigned in a single go,
// separated by commas
const myObj = {},
      str = 'myString',
      rand = Math.random(),
      anotherObj = {};

// Now, creating additional properties.
myObj.type              = 'Dot syntax for a key named type';
myObj['date created']   = 'This key has a space';
myObj[str]              = 'This key is in variable str';
myObj[rand]             = 'A random number is the key here';
myObj[anotherObj]       = 'This key is object anotherObj';
myObj['']               = 'This key is an empty string';

console.log(myObj);
console.log(myObj.myString);

/*
[Log] Object
    : "This key is an empty string"
    0.8916485437228595: "A random number is the key here"
    [object Object]: "This key is object anotherObj"
    date created: "This key has a space"
    myString: "This key is in variable str"
    type: "Dot syntax for a key named type"
*/
// notice that in the log, the order of the properties listed is not the same as the order they were created.

// [Log] This key is in variable str
8 đó là tên thuộc tính. Do đó,
str = 'myString';
myObj[str] = 'This key is in variable str';

console.log(myObj.str); //[Log] undefined

console.log(myObj[str]); //[Log] This key is in variable str
console.log(myObj.myString); //[Log] This key is in variable str
0 sẽ trở lại như không xác định.

str = 'myString';
myObj[str] = 'This key is in variable str';

console.log(myObj.str); //[Log] undefined

console.log(myObj[str]); //[Log] This key is in variable str
console.log(myObj.myString); //[Log] This key is in variable str

Điều này cho phép truy cập bất kỳ thuộc tính nào như được xác định trong thời gian chạy:

let propertyName = 'make';
myCar[propertyName] = 'Ford';

// access different properties by changing the contents of the variable
propertyName = 'model';
myCar[propertyName] = 'Mustang';

console.log(myCar);

// [Log] {make: 'Ford', model: 'Mustang'}

Bạn có thể sử dụng ký hiệu khung với

str = 'myString';
myObj[str] = 'This key is in variable str';

console.log(myObj.str); //[Log] undefined

console.log(myObj[str]); //[Log] This key is in variable str
console.log(myObj.myString); //[Log] This key is in variable str
1 để lặp lại trên tất cả các thuộc tính có thể suy giảm của một đối tượng. Để minh họa cách hoạt động của nó, hàm sau hiển thị các thuộc tính của đối tượng khi bạn chuyển tên đối tượng và tên của đối tượng làm đối số cho hàm:

function showProps(obj, objName) {
  let result = '';
  for (const i in obj) {
    // obj.hasOwn is used to exclude properties from the object's prototype chain and only show "own properties"
    if (Object.hasOwn(obj, i)) {
      result += `${objName}.${i} = ${obj[i]}\n`;
    }
  }
  console.log(result);
}

Thuật ngữ "thuộc tính riêng" đề cập đến các thuộc tính của đối tượng, nhưng không bao gồm các thuộc tính của chuỗi nguyên mẫu. Vì vậy, chức năng gọi

str = 'myString';
myObj[str] = 'This key is in variable str';

console.log(myObj.str); //[Log] undefined

console.log(myObj[str]); //[Log] This key is in variable str
console.log(myObj.myString); //[Log] This key is in variable str
2 sẽ in như sau:

myCar.make = Ford
myCar.model = Mustang
myCar.year = 1969

Liệt kê các thuộc tính của một đối tượng

Có ba cách gốc để liệt kê/Traverse Object Properties:

  • str = 'myString';
    myObj[str] = 'This key is in variable str';
    
    console.log(myObj.str); //[Log] undefined
    
    console.log(myObj[str]); //[Log] This key is in variable str
    console.log(myObj.myString); //[Log] This key is in variable str
    
    1 vòng lặp. Phương pháp này đi qua tất cả các thuộc tính chuỗi có thể suy giảm của một đối tượng cũng như chuỗi nguyên mẫu của nó.
  • str = 'myString';
    myObj[str] = 'This key is in variable str';
    
    console.log(myObj.str); //[Log] undefined
    
    console.log(myObj[str]); //[Log] This key is in variable str
    console.log(myObj.myString); //[Log] This key is in variable str
    
    4. Phương thức này trả về một mảng chỉ có tên thuộc tính chuỗi riêng ("phím") trong đối tượng
    // four variables are created and assigned in a single go,
    // separated by commas
    const myObj = {},
          str = 'myString',
          rand = Math.random(),
          anotherObj = {};
    
    // Now, creating additional properties.
    myObj.type              = 'Dot syntax for a key named type';
    myObj['date created']   = 'This key has a space';
    myObj[str]              = 'This key is in variable str';
    myObj[rand]             = 'A random number is the key here';
    myObj[anotherObj]       = 'This key is object anotherObj';
    myObj['']               = 'This key is an empty string';
    
    console.log(myObj);
    console.log(myObj.myString);
    
    /*
    [Log] Object
        : "This key is an empty string"
        0.8916485437228595: "A random number is the key here"
        [object Object]: "This key is object anotherObj"
        date created: "This key has a space"
        myString: "This key is in variable str"
        type: "Dot syntax for a key named type"
    */
    // notice that in the log, the order of the properties listed is not the same as the order they were created.
    
    // [Log] This key is in variable str
    
    4, nhưng không phải là trong chuỗi nguyên mẫu.
  • str = 'myString';
    myObj[str] = 'This key is in variable str';
    
    console.log(myObj.str); //[Log] undefined
    
    console.log(myObj[str]); //[Log] This key is in variable str
    console.log(myObj.myString); //[Log] This key is in variable str
    
    6. Phương thức này trả về một mảng chứa tất cả các tên thuộc tính chuỗi riêng trong đối tượng
    // four variables are created and assigned in a single go,
    // separated by commas
    const myObj = {},
          str = 'myString',
          rand = Math.random(),
          anotherObj = {};
    
    // Now, creating additional properties.
    myObj.type              = 'Dot syntax for a key named type';
    myObj['date created']   = 'This key has a space';
    myObj[str]              = 'This key is in variable str';
    myObj[rand]             = 'A random number is the key here';
    myObj[anotherObj]       = 'This key is object anotherObj';
    myObj['']               = 'This key is an empty string';
    
    console.log(myObj);
    console.log(myObj.myString);
    
    /*
    [Log] Object
        : "This key is an empty string"
        0.8916485437228595: "A random number is the key here"
        [object Object]: "This key is object anotherObj"
        date created: "This key has a space"
        myString: "This key is in variable str"
        type: "Dot syntax for a key named type"
    */
    // notice that in the log, the order of the properties listed is not the same as the order they were created.
    
    // [Log] This key is in variable str
    
    4, bất kể chúng có thể không có được hay không.

Không có cách tự nhiên để liệt kê các thuộc tính "ẩn" (thuộc tính trong chuỗi nguyên mẫu không thể truy cập được thông qua đối tượng, bởi vì một thuộc tính khác có cùng tên trước đó trong chuỗi nguyên mẫu). Tuy nhiên, điều này có thể đạt được với chức năng sau:

function listAllProperties(myObj) {
  let objectToInspect = myObj;
  let result = [];

  while(objectToInspect !== null) {
    result = result.concat(Object.getOwnPropertyNames(objectToInspect));
    objectToInspect = Object.getPrototypeOf(objectToInspect)
  }

  return result;
}

Tạo các đối tượng mới

JavaScript có một số đối tượng được xác định trước. Ngoài ra, bạn có thể tạo các đối tượng của riêng bạn. Bạn có thể tạo một đối tượng bằng Trình khởi tạo đối tượng. Ngoài ra, trước tiên bạn có thể tạo hàm tạo hàm và sau đó khởi tạo một đối tượng gọi hàm đó kết hợp với toán tử

str = 'myString';
myObj[str] = 'This key is in variable str';

console.log(myObj.str); //[Log] undefined

console.log(myObj[str]); //[Log] This key is in variable str
console.log(myObj.myString); //[Log] This key is in variable str
8.

Sử dụng các bộ khởi tạo đối tượng

Sử dụng các bộ khởi tạo đối tượng đôi khi được gọi là tạo các đối tượng có ký hiệu theo nghĩa đen. "Bộ khởi tạo đối tượng" phù hợp với thuật ngữ được sử dụng bởi C ++.

Cú pháp cho một đối tượng sử dụng Trình khởi tạo đối tượng là:

const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
0

Trong đó

str = 'myString';
myObj[str] = 'This key is in variable str';

console.log(myObj.str); //[Log] undefined

console.log(myObj[str]); //[Log] This key is in variable str
console.log(myObj.myString); //[Log] This key is in variable str
9 là tên của đối tượng mới, mỗi tên thuộc tính trước dấu chấm là một định danh (tên, một số hoặc một chuỗi theo nghĩa đen) và mỗi
let propertyName = 'make';
myCar[propertyName] = 'Ford';

// access different properties by changing the contents of the variable
propertyName = 'model';
myCar[propertyName] = 'Mustang';

console.log(myCar);

// [Log] {make: 'Ford', model: 'Mustang'}
0 là một biểu thức có giá trị được gán cho tên thuộc tính.
str = 'myString';
myObj[str] = 'This key is in variable str';

console.log(myObj.str); //[Log] undefined

console.log(myObj[str]); //[Log] This key is in variable str
console.log(myObj.myString); //[Log] This key is in variable str
9 và chuyển nhượng là tùy chọn; Nếu bạn không cần phải tham khảo đối tượng này ở nơi khác, bạn không cần phải gán nó cho một biến. .

Bộ khởi tạo đối tượng là các biểu thức và mỗi trình khởi tạo đối tượng dẫn đến một đối tượng mới được tạo bất cứ khi nào câu lệnh xuất hiện được thực thi. Bộ khởi tạo đối tượng giống hệt nhau tạo ra các đối tượng riêng biệt sẽ không so sánh với nhau như nhau. Các đối tượng được tạo như thể một cuộc gọi đến

let propertyName = 'make';
myCar[propertyName] = 'Ford';

// access different properties by changing the contents of the variable
propertyName = 'model';
myCar[propertyName] = 'Mustang';

console.log(myCar);

// [Log] {make: 'Ford', model: 'Mustang'}
2 đã được thực hiện; Đó là, các đối tượng được làm từ các biểu thức theo nghĩa đen của đối tượng là các trường hợp của
let propertyName = 'make';
myCar[propertyName] = 'Ford';

// access different properties by changing the contents of the variable
propertyName = 'model';
myCar[propertyName] = 'Mustang';

console.log(myCar);

// [Log] {make: 'Ford', model: 'Mustang'}
3.

Câu lệnh sau đây tạo một đối tượng và gán nó cho biến

let propertyName = 'make';
myCar[propertyName] = 'Ford';

// access different properties by changing the contents of the variable
propertyName = 'model';
myCar[propertyName] = 'Mustang';

console.log(myCar);

// [Log] {make: 'Ford', model: 'Mustang'}
4 khi và chỉ khi biểu thức
let propertyName = 'make';
myCar[propertyName] = 'Ford';

// access different properties by changing the contents of the variable
propertyName = 'model';
myCar[propertyName] = 'Mustang';

console.log(myCar);

// [Log] {make: 'Ford', model: 'Mustang'}
5 là đúng:

const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
1

Ví dụ sau đây tạo ra

let propertyName = 'make';
myCar[propertyName] = 'Ford';

// access different properties by changing the contents of the variable
propertyName = 'model';
myCar[propertyName] = 'Mustang';

console.log(myCar);

// [Log] {make: 'Ford', model: 'Mustang'}
6 với ba thuộc tính. Lưu ý rằng thuộc tính
let propertyName = 'make';
myCar[propertyName] = 'Ford';

// access different properties by changing the contents of the variable
propertyName = 'model';
myCar[propertyName] = 'Mustang';

console.log(myCar);

// [Log] {make: 'Ford', model: 'Mustang'}
7 cũng là một đối tượng có thuộc tính riêng của nó.

const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
2

Bạn cũng có thể sử dụng bộ khởi tạo đối tượng để tạo mảng. Xem văn bản mảng.

Sử dụng hàm tạo hàm

Ngoài ra, bạn có thể tạo một đối tượng với hai bước sau:

  1. Xác định loại đối tượng bằng cách viết hàm tạo hàm. Có một quy ước mạnh mẽ, với lý do chính đáng, để sử dụng một lá thư ban đầu vốn.
  2. Tạo một thể hiện của đối tượng với
    str = 'myString';
    myObj[str] = 'This key is in variable str';
    
    console.log(myObj.str); //[Log] undefined
    
    console.log(myObj[str]); //[Log] This key is in variable str
    console.log(myObj.myString); //[Log] This key is in variable str
    
    8.

Để xác định loại đối tượng, hãy tạo một hàm cho loại đối tượng chỉ định tên, thuộc tính và phương thức của nó. Ví dụ: giả sử bạn muốn tạo một loại đối tượng cho xe hơi. Bạn muốn loại đối tượng này được gọi là

let propertyName = 'make';
myCar[propertyName] = 'Ford';

// access different properties by changing the contents of the variable
propertyName = 'model';
myCar[propertyName] = 'Mustang';

console.log(myCar);

// [Log] {make: 'Ford', model: 'Mustang'}
9 và bạn muốn nó có thuộc tính để tạo, mô hình và năm. Để làm điều này, bạn sẽ viết chức năng sau:

const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
3

Lưu ý rằng việc sử dụng

function showProps(obj, objName) {
  let result = '';
  for (const i in obj) {
    // obj.hasOwn is used to exclude properties from the object's prototype chain and only show "own properties"
    if (Object.hasOwn(obj, i)) {
      result += `${objName}.${i} = ${obj[i]}\n`;
    }
  }
  console.log(result);
}
0 để gán các giá trị cho các thuộc tính của đối tượng dựa trên các giá trị được truyền cho hàm.

Bây giờ bạn có thể tạo một đối tượng được gọi là

myCar['make'] = 'Ford';
myCar['model'] = 'Mustang';
myCar['year'] = 1969;
5 như sau:

const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
4

Câu lệnh này tạo ra

myCar['make'] = 'Ford';
myCar['model'] = 'Mustang';
myCar['year'] = 1969;
5 và gán nó các giá trị được chỉ định cho các thuộc tính của nó. Sau đó, giá trị của
function showProps(obj, objName) {
  let result = '';
  for (const i in obj) {
    // obj.hasOwn is used to exclude properties from the object's prototype chain and only show "own properties"
    if (Object.hasOwn(obj, i)) {
      result += `${objName}.${i} = ${obj[i]}\n`;
    }
  }
  console.log(result);
}
3 là chuỗi "đại bàng",
function showProps(obj, objName) {
  let result = '';
  for (const i in obj) {
    // obj.hasOwn is used to exclude properties from the object's prototype chain and only show "own properties"
    if (Object.hasOwn(obj, i)) {
      result += `${objName}.${i} = ${obj[i]}\n`;
    }
  }
  console.log(result);
}
4 là chuỗi 'Talon TSI',
function showProps(obj, objName) {
  let result = '';
  for (const i in obj) {
    // obj.hasOwn is used to exclude properties from the object's prototype chain and only show "own properties"
    if (Object.hasOwn(obj, i)) {
      result += `${objName}.${i} = ${obj[i]}\n`;
    }
  }
  console.log(result);
}
5 là số nguyên năm 1993, v.v. Thứ tự của các đối số và tham số nên giống nhau.

Bạn có thể tạo bất kỳ số lượng đối tượng

let propertyName = 'make';
myCar[propertyName] = 'Ford';

// access different properties by changing the contents of the variable
propertyName = 'model';
myCar[propertyName] = 'Mustang';

console.log(myCar);

// [Log] {make: 'Ford', model: 'Mustang'}
9 bằng các cuộc gọi đến
str = 'myString';
myObj[str] = 'This key is in variable str';

console.log(myObj.str); //[Log] undefined

console.log(myObj[str]); //[Log] This key is in variable str
console.log(myObj.myString); //[Log] This key is in variable str
8. Ví dụ,

const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
5

Một đối tượng có thể có một thuộc tính tự nó là một đối tượng khác. Ví dụ: giả sử bạn xác định một đối tượng được gọi là

function showProps(obj, objName) {
  let result = '';
  for (const i in obj) {
    // obj.hasOwn is used to exclude properties from the object's prototype chain and only show "own properties"
    if (Object.hasOwn(obj, i)) {
      result += `${objName}.${i} = ${obj[i]}\n`;
    }
  }
  console.log(result);
}
8 như sau:

const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
6

và sau đó khởi tạo hai đối tượng

function showProps(obj, objName) {
  let result = '';
  for (const i in obj) {
    // obj.hasOwn is used to exclude properties from the object's prototype chain and only show "own properties"
    if (Object.hasOwn(obj, i)) {
      result += `${objName}.${i} = ${obj[i]}\n`;
    }
  }
  console.log(result);
}
8 mới như sau:

const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
7

Sau đó, bạn có thể viết lại định nghĩa của

let propertyName = 'make';
myCar[propertyName] = 'Ford';

// access different properties by changing the contents of the variable
propertyName = 'model';
myCar[propertyName] = 'Mustang';

console.log(myCar);

// [Log] {make: 'Ford', model: 'Mustang'}
9 để bao gồm một thuộc tính
myCar.make = Ford
myCar.model = Mustang
myCar.year = 1969
1 có đối tượng
function showProps(obj, objName) {
  let result = '';
  for (const i in obj) {
    // obj.hasOwn is used to exclude properties from the object's prototype chain and only show "own properties"
    if (Object.hasOwn(obj, i)) {
      result += `${objName}.${i} = ${obj[i]}\n`;
    }
  }
  console.log(result);
}
8, như sau:

const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
8

Để khởi tạo các đối tượng mới, sau đó bạn sử dụng các đối tượng sau:

const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
9

Lưu ý rằng thay vì truyền một chuỗi theo nghĩa đen hoặc giá trị số nguyên khi tạo các đối tượng mới, các câu lệnh trên truyền các đối tượng

myCar.make = Ford
myCar.model = Mustang
myCar.year = 1969
3 và
myCar.make = Ford
myCar.model = Mustang
myCar.year = 1969
4 làm đối số cho chủ sở hữu. Sau đó, nếu bạn muốn tìm ra tên của chủ sở hữu của
myCar.make = Ford
myCar.model = Mustang
myCar.year = 1969
5, bạn có thể truy cập thuộc tính sau:

Lưu ý rằng bạn luôn có thể thêm một thuộc tính vào một đối tượng được xác định trước đó. Ví dụ: tuyên bố

Thêm một thuộc tính

myCar.make = Ford
myCar.model = Mustang
myCar.year = 1969
6 vào
myCar.make = Ford
myCar.model = Mustang
myCar.year = 1969
7 và gán cho nó một giá trị là
myCar.make = Ford
myCar.model = Mustang
myCar.year = 1969
8. Tuy nhiên, điều này không ảnh hưởng đến bất kỳ đối tượng nào khác. Để thêm thuộc tính mới vào tất cả các đối tượng cùng loại, bạn phải thêm thuộc tính vào định nghĩa của loại đối tượng
let propertyName = 'make';
myCar[propertyName] = 'Ford';

// access different properties by changing the contents of the variable
propertyName = 'model';
myCar[propertyName] = 'Mustang';

console.log(myCar);

// [Log] {make: 'Ford', model: 'Mustang'}
9.

Sử dụng phương pháp function listAllProperties(myObj) { let objectToInspect = myObj; let result = []; while(objectToInspect !== null) { result = result.concat(Object.getOwnPropertyNames(objectToInspect)); objectToInspect = Object.getPrototypeOf(objectToInspect) } return result; } 0

Các đối tượng cũng có thể được tạo bằng phương thức

function listAllProperties(myObj) {
  let objectToInspect = myObj;
  let result = [];

  while(objectToInspect !== null) {
    result = result.concat(Object.getOwnPropertyNames(objectToInspect));
    objectToInspect = Object.getPrototypeOf(objectToInspect)
  }

  return result;
}
1. Phương pháp này có thể rất hữu ích, bởi vì nó cho phép bạn chọn đối tượng nguyên mẫu cho đối tượng bạn muốn tạo, mà không phải xác định hàm tạo hàm.

myCar.color; // undefined
0

Di sản

Tất cả các đối tượng trong JavaScript kế thừa từ ít nhất một đối tượng khác. Đối tượng được di truyền từ được gọi là nguyên mẫu và các thuộc tính được di truyền có thể được tìm thấy trong đối tượng

function listAllProperties(myObj) {
  let objectToInspect = myObj;
  let result = [];

  while(objectToInspect !== null) {
    result = result.concat(Object.getOwnPropertyNames(objectToInspect));
    objectToInspect = Object.getPrototypeOf(objectToInspect)
  }

  return result;
}
2 của hàm tạo. Xem kế thừa và chuỗi nguyên mẫu để biết thêm thông tin.

Lập chỉ mục các thuộc tính đối tượng

Bạn có thể tham khảo một thuộc tính của một đối tượng bằng tên thuộc tính của nó hoặc theo chỉ số thứ tự của nó. Nếu ban đầu bạn xác định một thuộc tính bằng tên của nó, bạn phải luôn tham khảo nó bằng tên của nó và nếu ban đầu bạn xác định một thuộc tính theo chỉ mục, bạn phải luôn luôn tham khảo nó bằng chỉ mục của nó.

Hạn chế này áp dụng khi bạn tạo một đối tượng và các thuộc tính của nó với hàm tạo hàm (như chúng tôi đã làm trước đây với loại đối tượng

let propertyName = 'make';
myCar[propertyName] = 'Ford';

// access different properties by changing the contents of the variable
propertyName = 'model';
myCar[propertyName] = 'Mustang';

console.log(myCar);

// [Log] {make: 'Ford', model: 'Mustang'}
9) và khi bạn xác định rõ ràng các thuộc tính riêng lẻ (ví dụ:
function listAllProperties(myObj) {
  let objectToInspect = myObj;
  let result = [];

  while(objectToInspect !== null) {
    result = result.concat(Object.getOwnPropertyNames(objectToInspect));
    objectToInspect = Object.getPrototypeOf(objectToInspect)
  }

  return result;
}
4). Nếu ban đầu bạn xác định một thuộc tính đối tượng có chỉ mục, chẳng hạn như
function listAllProperties(myObj) {
  let objectToInspect = myObj;
  let result = [];

  while(objectToInspect !== null) {
    result = result.concat(Object.getOwnPropertyNames(objectToInspect));
    objectToInspect = Object.getPrototypeOf(objectToInspect)
  }

  return result;
}
5, sau đó bạn chỉ tham khảo thuộc tính này là
function listAllProperties(myObj) {
  let objectToInspect = myObj;
  let result = [];

  while(objectToInspect !== null) {
    result = result.concat(Object.getOwnPropertyNames(objectToInspect));
    objectToInspect = Object.getPrototypeOf(objectToInspect)
  }

  return result;
}
6.

Ngoại lệ cho quy tắc này là các đối tượng giống như mảng được phản ánh từ HTML, chẳng hạn như đối tượng giống như mảng

function listAllProperties(myObj) {
  let objectToInspect = myObj;
  let result = [];

  while(objectToInspect !== null) {
    result = result.concat(Object.getOwnPropertyNames(objectToInspect));
    objectToInspect = Object.getPrototypeOf(objectToInspect)
  }

  return result;
}
7. Bạn luôn có thể tham khảo các đối tượng trong các đối tượng giống như mảng này bằng số thứ tự của chúng (dựa trên nơi chúng xuất hiện trong tài liệu) hoặc tên của chúng (nếu được xác định). Ví dụ: nếu thẻ
function listAllProperties(myObj) {
  let objectToInspect = myObj;
  let result = [];

  while(objectToInspect !== null) {
    result = result.concat(Object.getOwnPropertyNames(objectToInspect));
    objectToInspect = Object.getPrototypeOf(objectToInspect)
  }

  return result;
}
8 thứ hai trong tài liệu có thuộc tính
function listAllProperties(myObj) {
  let objectToInspect = myObj;
  let result = [];

  while(objectToInspect !== null) {
    result = result.concat(Object.getOwnPropertyNames(objectToInspect));
    objectToInspect = Object.getPrototypeOf(objectToInspect)
  }

  return result;
}
9, bạn có thể gọi biểu mẫu là
const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
00 hoặc
const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
01 hoặc
const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
02.

Xác định thuộc tính cho loại đối tượng

Bạn có thể thêm thuộc tính vào loại đối tượng được xác định trước đó bằng cách sử dụng thuộc tính

function listAllProperties(myObj) {
  let objectToInspect = myObj;
  let result = [];

  while(objectToInspect !== null) {
    result = result.concat(Object.getOwnPropertyNames(objectToInspect));
    objectToInspect = Object.getPrototypeOf(objectToInspect)
  }

  return result;
}
2. Điều này xác định một thuộc tính được chia sẻ bởi tất cả các đối tượng thuộc loại được chỉ định, thay vì chỉ bằng một thể hiện của đối tượng. Mã sau đây thêm thuộc tính
myCar.make = Ford
myCar.model = Mustang
myCar.year = 1969
6 cho tất cả các đối tượng thuộc loại
let propertyName = 'make';
myCar[propertyName] = 'Ford';

// access different properties by changing the contents of the variable
propertyName = 'model';
myCar[propertyName] = 'Mustang';

console.log(myCar);

// [Log] {make: 'Ford', model: 'Mustang'}
9, sau đó gán một giá trị cho thuộc tính
myCar.make = Ford
myCar.model = Mustang
myCar.year = 1969
6 của đối tượng
myCar.make = Ford
myCar.model = Mustang
myCar.year = 1969
7.

myCar.color; // undefined
1

Xem kế thừa_and_the_prototype_chain để biết thêm thông tin.

Xác định phương pháp

Phương pháp là một hàm được liên kết với một đối tượng, hoặc, khác nhau, một phương thức là một thuộc tính của một đối tượng là một hàm. Các phương thức được xác định theo cách xác định các hàm bình thường, ngoại trừ việc chúng phải được gán là thuộc tính của một đối tượng. Xem thêm Định nghĩa phương pháp để biết thêm chi tiết. Một ví dụ là:

myCar.color; // undefined
2

Trong đó

const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
08 là một đối tượng hiện có,
const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
09 là tên bạn đang gán cho phương thức và
const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
10 là tên của hàm.

Sau đó, bạn có thể gọi phương thức trong bối cảnh của đối tượng như sau:

myCar.color; // undefined
3

Bạn có thể xác định các phương thức cho một loại đối tượng bằng cách bao gồm một định nghĩa phương thức trong hàm xây dựng đối tượng. Bạn có thể xác định một hàm sẽ định dạng và hiển thị các thuộc tính của các đối tượng

let propertyName = 'make';
myCar[propertyName] = 'Ford';

// access different properties by changing the contents of the variable
propertyName = 'model';
myCar[propertyName] = 'Mustang';

console.log(myCar);

// [Log] {make: 'Ford', model: 'Mustang'}
9 được xác định trước đó; Ví dụ,

myCar.color; // undefined
4

trong đó

const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
12 là một hàm để hiển thị quy tắc ngang và chuỗi. Lưu ý rằng việc sử dụng
function showProps(obj, objName) {
  let result = '';
  for (const i in obj) {
    // obj.hasOwn is used to exclude properties from the object's prototype chain and only show "own properties"
    if (Object.hasOwn(obj, i)) {
      result += `${objName}.${i} = ${obj[i]}\n`;
    }
  }
  console.log(result);
}
0 để tham khảo đối tượng mà phương thức thuộc về.

Bạn có thể biến hàm này thành một phương thức của

let propertyName = 'make';
myCar[propertyName] = 'Ford';

// access different properties by changing the contents of the variable
propertyName = 'model';
myCar[propertyName] = 'Mustang';

console.log(myCar);

// [Log] {make: 'Ford', model: 'Mustang'}
9 bằng cách thêm câu lệnh

myCar.color; // undefined
5

đến định nghĩa đối tượng. Vì vậy, định nghĩa đầy đủ của

let propertyName = 'make';
myCar[propertyName] = 'Ford';

// access different properties by changing the contents of the variable
propertyName = 'model';
myCar[propertyName] = 'Mustang';

console.log(myCar);

// [Log] {make: 'Ford', model: 'Mustang'}
9 bây giờ sẽ trông giống như

myCar.color; // undefined
6

Sau đó, bạn có thể gọi phương thức

const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
16 cho từng đối tượng như sau:

myCar.color; // undefined
7

Sử dụng function showProps(obj, objName) { let result = ''; for (const i in obj) { // obj.hasOwn is used to exclude properties from the object's prototype chain and only show "own properties" if (Object.hasOwn(obj, i)) { result += `${objName}.${i} = ${obj[i]}\n`; } } console.log(result); } 0 cho các tài liệu tham khảo đối tượng

JavaScript có một từ khóa đặc biệt,

function showProps(obj, objName) {
  let result = '';
  for (const i in obj) {
    // obj.hasOwn is used to exclude properties from the object's prototype chain and only show "own properties"
    if (Object.hasOwn(obj, i)) {
      result += `${objName}.${i} = ${obj[i]}\n`;
    }
  }
  console.log(result);
}
0, mà bạn có thể sử dụng trong một phương thức để chỉ đối tượng hiện tại. Ví dụ: giả sử bạn có 2 đối tượng,
const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
19 và
const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
20. Mỗi đối tượng có
const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
21,
const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
22 và
const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
23 của riêng họ. Trong hàm
const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
24, thông báo có
const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
25. Khi được thêm vào 2 đối tượng, chúng có thể được gọi và in
const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
26 sau đó thêm giá trị
const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
21 từ đối tượng cụ thể đó. Như hình dưới đây.

myCar.color; // undefined
8

function showProps(obj, objName) {
  let result = '';
  for (const i in obj) {
    // obj.hasOwn is used to exclude properties from the object's prototype chain and only show "own properties"
    if (Object.hasOwn(obj, i)) {
      result += `${objName}.${i} = ${obj[i]}\n`;
    }
  }
  console.log(result);
}
0 đề cập đến đối tượng mà nó đang ở. Bạn có thể tạo một chức năng mới gọi là
const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
29 đăng nhập một câu cho biết người đó bao nhiêu tuổi.

myCar.color; // undefined
9

Xác định getters và setters

Getter là một phương pháp nhận được giá trị của một thuộc tính cụ thể. Một setter là một phương thức đặt giá trị của một thuộc tính cụ thể. Bạn có thể xác định getters và setters trên bất kỳ đối tượng lõi được xác định trước hoặc đối tượng do người dùng xác định hỗ trợ bổ sung các thuộc tính mới.

Getters và setters có thể là

  • được xác định bằng cách sử dụng khởi tạo đối tượng hoặc
  • Đã thêm sau vào bất kỳ đối tượng nào bất cứ lúc nào bằng phương thức thêm getter hoặc setter.

Khi xác định getters và setters sử dụng bộ khởi tạo đối tượng, tất cả những gì bạn cần làm là tiền tố phương thức getter với

const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
30 và phương thức setter với
const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
31. Tất nhiên, phương thức Getter không được mong đợi một tham số, trong khi phương thức Setter mong đợi chính xác một tham số (giá trị mới để đặt). Ví dụ:

myCar['make'] = 'Ford';
myCar['model'] = 'Mustang';
myCar['year'] = 1969;
0

Các thuộc tính của đối tượng

// four variables are created and assigned in a single go,
// separated by commas
const myObj = {},
      str = 'myString',
      rand = Math.random(),
      anotherObj = {};

// Now, creating additional properties.
myObj.type              = 'Dot syntax for a key named type';
myObj['date created']   = 'This key has a space';
myObj[str]              = 'This key is in variable str';
myObj[rand]             = 'A random number is the key here';
myObj[anotherObj]       = 'This key is object anotherObj';
myObj['']               = 'This key is an empty string';

console.log(myObj);
console.log(myObj.myString);

/*
[Log] Object
    : "This key is an empty string"
    0.8916485437228595: "A random number is the key here"
    [object Object]: "This key is object anotherObj"
    date created: "This key has a space"
    myString: "This key is in variable str"
    type: "Dot syntax for a key named type"
*/
// notice that in the log, the order of the properties listed is not the same as the order they were created.

// [Log] This key is in variable str
4 là:

  • const myCar = {
      make: 'Ford',
      model: 'Mustang',
      year: 1969
    };
    
    33 - một số
  • const myCar = {
      make: 'Ford',
      model: 'Mustang',
      year: 1969
    };
    
    34 - một người nhận trả về
    const myCar = {
      make: 'Ford',
      model: 'Mustang',
      year: 1969
    };
    
    33 cộng với 1
  • const myCar = {
      make: 'Ford',
      model: 'Mustang',
      year: 1969
    };
    
    36 - Một setter đặt giá trị của
    const myCar = {
      make: 'Ford',
      model: 'Mustang',
      year: 1969
    };
    
    33 thành một nửa giá trị
    const myCar = {
      make: 'Ford',
      model: 'Mustang',
      year: 1969
    };
    
    36 đang được đặt thành

Xin lưu ý rằng tên hàm của getters và setters được xác định trong một đối tượng theo nghĩa đen bằng cách sử dụng "[gs] et property ()" không phải là tên của chính các getters, mặc dù cú pháp

const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
39 có thể đánh lừa bạn nghĩ khác.

Getters và setters cũng có thể được thêm vào một đối tượng bất cứ lúc nào sau khi tạo bằng phương thức

const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
40. Tham số đầu tiên của phương thức này là đối tượng mà bạn muốn xác định getter hoặc setter. Tham số thứ hai là một đối tượng có tên thuộc tính là tên getter hoặc setter và có giá trị thuộc tính là đối tượng để xác định các hàm getter hoặc setter. Dưới đây là một ví dụ xác định cùng một getter và setter được sử dụng trong ví dụ trước:

myCar['make'] = 'Ford';
myCar['model'] = 'Mustang';
myCar['year'] = 1969;
1

Những hình thức nào trong hai hình thức để chọn phụ thuộc vào phong cách lập trình và nhiệm vụ của bạn trong tay. Nếu bạn đã sử dụng trình khởi tạo đối tượng khi xác định nguyên mẫu, bạn có thể sẽ chọn biểu mẫu đầu tiên. Hình thức này nhỏ gọn và tự nhiên hơn. Tuy nhiên, nếu bạn cần thêm getters và setters sau - vì bạn không viết nguyên mẫu hoặc đối tượng cụ thể - thì biểu mẫu thứ hai là biểu mẫu duy nhất có thể. Hình thức thứ hai có thể thể hiện tốt nhất bản chất năng động của JavaScript - nhưng nó có thể làm cho mã khó đọc và hiểu.

Xóa thuộc tính

Bạn có thể xóa một thuộc tính không được inher bằng cách sử dụng toán tử

const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
41. Mã sau đây cho thấy cách xóa một thuộc tính.

myCar['make'] = 'Ford';
myCar['model'] = 'Mustang';
myCar['year'] = 1969;
2

So sánh các đối tượng

Trong JavaScript, các đối tượng là một loại tham chiếu. Hai đối tượng riêng biệt không bao giờ bằng nhau, ngay cả khi chúng có cùng thuộc tính. Chỉ so sánh cùng một tham chiếu đối tượng với chính nó mang lại đúng.

myCar['make'] = 'Ford';
myCar['model'] = 'Mustang';
myCar['year'] = 1969;
3

myCar['make'] = 'Ford';
myCar['model'] = 'Mustang';
myCar['year'] = 1969;
4

Để biết thêm thông tin về các nhà khai thác so sánh, hãy xem các nhà khai thác bình đẳng.

Xem thêm

  • Để lặn sâu hơn, hãy đọc về kế thừa và chuỗi nguyên mẫu.
  • Để tìm hiểu về các lớp (một cách khác để tạo các đối tượng), hãy đọc tham chiếu của các lớp JavaScript.
  • " Trước
  • Tiếp theo "