• 0366 997 840
  • namdong92@gmail.com

Object


 

Đối tượng là kiểu dữ liệu không nguyên thủy trong JavaScript. Nó giống như bất kỳ biến nào khác, sự khác biệt duy nhất là một đối tượng chứa nhiều giá trị về các thuộc tính và phương thức. Các thuộc tính có thể chứa các giá trị của các kiểu dữ liệu nguyên thủy và các phương thức là các hàm.

Let's learn how to create an object in JavaScript.

In JavaScript, an object can be created in two ways:

  1. Object literal
  2. Object constructor

Object Literal

The object literal is a simple way of creating an object using { } brackets. You can include key-value pair in { }, where key would be property or method name and value will be value of property of any data type or a function. Use comma (,) to separate multiple key-value pairs.

Syntax:
var <object-name> = { key1: value1, key2: value2,... keyN: valueN};

The following example creates an object using object literal syntax.

Example: Create Object using Object Literal Syntax
var emptyObject = {}; // object with no properties or methods
var person = { firstName: "John" }; // object with single property
// object with single method
var message = { showMessage: function (val) { alert(val); } };
// object with properties & method
var person = { firstName: "James", lastName: "Bond", age: 15, getFullName: function () { return this.firstName + ' ' + this.lastName } };

You must specify key-value pair in object for properties or methods. Only property or method name without value is not valid. The following syntax is invalid.

Example: Wrong Syntax
var person = { firstName };
var person = { firstName: };

Access JavaScript Object Properties & Methods

You can get or set values of an object's properties using dot notation or bracket. However, you can call an object's method only using dot notation.

Example: Access JS Object
var person = { firstName: "James", lastName: "Bond", age: 25, getFullName: function () { return this.firstName + ' ' + this.lastName } };
person.firstName; // returns James
person.lastName; // returns Bond
person["firstName"];// returns James
person["lastName"];// returns Bond
person.getFullName();

 

 Note:
An object's methods can be called using () operator e.g. person.getFullName(). Without (), it will return function definition.

Object Constructor

The second way to create an object is with Object Constructor using new keyword. You can attach properties and methods using dot notation. Optionally, you can also create properties using [ ] brackets and specifying property name as string.

Example: Object Constructor
var person = new Object();
// Attach properties and methods to person object 
person.firstName = "James";
person["lastName"] = "Bond";
person.age = 25;
person.getFullName = function () { return this.firstName + ' ' + this.lastName; };
// access properties & methods 
person.firstName; // James
person.lastName; // Bond
person.getFullName(); // James Bond

Undefined Property or Method

JavaScript will return 'undefined' if you try to access properties or call methods that do not exist.

If you are not sure whether an object has a particular property or not, then use hasOwnProperty() method before accessing properties.

Example: hasOwnProperty()
var person = new Object();
person.firstName; // returns undefined
if(person.hasOwnProperty("firstName")){ person.firstName; }

Access Object Keys.

Use for..in loop to get the list of all properties and methods of an object.

Example: Access Object Keys
var person = new Object();
person.firstName = "James";
person["lastName"] = "Bond";
person.age = 25;
person.getFullName = function () { return this.firstName + ' ' + this.lastName; };
for(var key in person){ alert(key); };

Pass by Reference

Object in JavaScript passes by reference from one function to another.

Example: JS Object Passes by Reference
function changeFirstName(per)
{ per.firstName = "Steve";
}
var person = { firstName : "Bill" };
changeFirstName(person)
person.firstName; // returns Steve

If, two objects point to the same object then the change made in one object will reflect in another object.

Example: Object Reference
var person = { firstName : "John" };
var anotherPerson = person;
anotherPerson.firstName = "Bill";
person.firstName; //returns Bill

You can assign another object as a property of an object.

Example: Nested JS Objects
var person = { firstName: "James", lastName: "Bond", age: 25, address: { id: 1, country:"UK" }
};
person.address.country; // returns "UK"
  1. JavaScript object is a standalone entity that holds multiple values in terms of properties and methods.
  2. Object property stores a literal value and method represents function.
  3. An object can be created using object literal or object constructor syntax.
  4. Object literal:
  5. var person = { firstName: "James", lastName: "Bond", age: 25, getFullName: function () { return this.firstName + ' ' + this.lastName }
    };
    
  6. Object constructor:
  7. var person = new Object();
    person.firstName = "James";
    person["lastName"] = "Bond";
    person.age = 25;
    person.getFullName = function () { return this.firstName + ' ' + this.lastName; };
    
  8. Object properties and methods can be accessed using dot notation or [ ] bracket.
  9. An object is passed by reference from one function to another.
  10. An object can include another object as a property.

Bài Liên Quan


Giới Thiệu JavaScript

Giới Thiệu JavaScript

JavaScript là ngôn ngữ kịch bản phía máy khách được gõ lỏng lẻo thực thi trong trình duyệt của người dùng. JavaScript tương tác với các phần tử html (phần tử DOM) để tạo giao diện người dùng web tương tác.

Javascript Căn Bản

Javascript Căn Bản

Bất kỳ loại tập lệnh phía máy khách nào cũng có thể được viết bên trong thẻ <script> bằng html. Thẻ script xác định một khối mã script trong trang html. Nó cũng tải một tập tin script với thuộc tính src.

Ajax trong lập trình web

Ajax trong lập trình web

Ajax (Asynchronous JavaScript and XML) - là một khái niệm được giới thiệu và sử dụng đầu tiền vào tháng 2 năm 2005. Ajax là thứ thâm ảo với các lập trình viên mới, với những nhà tuyển dụng nó là thứ gì đó cao siêu đánh giá khả năng của lập trình viên, với maketing cho các khóa hoc nó được đưa lên một tầm cao mới là "võ công thượng thừa"  mà một lập trình viên phải đạt được, không ít người nhầm lẫn AJAX là ngôn ngữ lập trình, hầu như khi nhắc đến ajax là lại nghĩ ngay đến jquery.

Vô hiệu hóa chuột phải và không cho người dùng chọn văn bản

Vô hiệu hóa chuột phải và không cho người dùng chọn văn bản

Trong một số trường hợp bạn không muốn cho người dùng trang web sử dụng chuột phải, và không cho chọn thành phần trang bạn có thể làm....

Danh Mục

Bài Viết Mới Nhất