- JavaScript Objects
- JavaScript Primitives
- Examples
- Immutable
- Objects are Variables
- Example
- Example
- Example
- Object Properties
- Object Methods
- Creating a JavaScript Object
- Using an Object Literal
- Example
- Example
- Example
- Using the JavaScript Keyword new
- Example
- JavaScript Objects are Mutable
- Example
- Object.create()
- Синтаксис
- Параметры
- Возвращаемые значения
- Выбрасываемые исключения
- Примеры
- Пример: классическое наследование с Object.create()
- Пример: использование аргумента propertiesObject с Object.create()
- Полифил
- Спецификации
- Совместимость с браузерами
- Смотрите также
JavaScript Objects
In JavaScript, objects are king. If you understand objects, you understand JavaScript.
In JavaScript, almost «everything» is an object.
- Booleans can be objects (if defined with the new keyword)
- Numbers can be objects (if defined with the new keyword)
- Strings can be objects (if defined with the new keyword)
- Dates are always objects
- Maths are always objects
- Regular expressions are always objects
- Arrays are always objects
- Functions are always objects
- Objects are always objects
All JavaScript values, except primitives, are objects.
JavaScript Primitives
A primitive value is a value that has no properties or methods.
3.14 is a primitive value
A primitive data type is data that has a primitive value.
JavaScript defines 7 types of primitive data types:
Examples
- string
- number
- boolean
- null
- undefined
- symbol
- bigint
Immutable
Primitive values are immutable (they are hardcoded and cannot be changed).
if x = 3.14, you can change the value of x, but you cannot change the value of 3.14.
Value | Type | Comment |
---|---|---|
«Hello» | string | «Hello» is always «Hello» |
3.14 | number | 3.14 is always 3.14 |
true | boolean | true is always true |
false | boolean | false is always false |
null | null (object) | null is always null |
undefined | undefined | undefined is always undefined |
Objects are Variables
JavaScript variables can contain single values:
Example
JavaScript variables can also contain many values.
Objects are variables too. But objects can contain many values.
Object values are written as name : value pairs (name and value separated by a colon).
Example
A JavaScript object is a collection of named values
It is a common practice to declare objects with the const keyword.
Example
Object Properties
The named values, in JavaScript objects, are called properties.
Property | Value |
---|---|
firstName | John |
lastName | Doe |
age | 50 |
eyeColor | blue |
Objects written as name value pairs are similar to:
- Associative arrays in PHP
- Dictionaries in Python
- Hash tables in C
- Hash maps in Java
- Hashes in Ruby and Perl
Object Methods
Methods are actions that can be performed on objects.
Object properties can be both primitive values, other objects, and functions.
An object method is an object property containing a function definition.
Property | Value |
---|---|
firstName | John |
lastName | Doe |
age | 50 |
eyeColor | blue |
fullName | function() |
JavaScript objects are containers for named values, called properties and methods.
You will learn more about methods in the next chapters.
Creating a JavaScript Object
With JavaScript, you can define and create your own objects.
There are different ways to create new objects:
- Create a single object, using an object literal.
- Create a single object, with the keyword new .
- Define an object constructor, and then create objects of the constructed type.
- Create an object using Object.create() .
Using an Object Literal
This is the easiest way to create a JavaScript Object.
Using an object literal, you both define and create an object in one statement.
An object literal is a list of name:value pairs (like age:50) inside curly braces <>.
The following example creates a new JavaScript object with four properties:
Example
Spaces and line breaks are not important. An object definition can span multiple lines:
Example
This example creates an empty JavaScript object, and then adds 4 properties:
Example
const person = <>;
person.firstName = «John»;
person.lastName = «Doe»;
person.age = 50;
person.eyeColor = «blue»;
Using the JavaScript Keyword new
The following example create a new JavaScript object using new Object() , and then adds 4 properties:
Example
const person = new Object();
person.firstName = «John»;
person.lastName = «Doe»;
person.age = 50;
person.eyeColor = «blue»;
The examples above do exactly the same.
But there is no need to use new Object() .
For readability, simplicity and execution speed, use the object literal method.
JavaScript Objects are Mutable
Objects are mutable: They are addressed by reference, not by value.
If person is an object, the following statement will not create a copy of person:
The object x is not a copy of person. It is person. Both x and person are the same object.
Any changes to x will also change person, because x and person are the same object.
Example
const person = <
firstName:»John»,
lastName:»Doe»,
age:50, eyeColor:»blue»
>
const x = person;
x.age = 10; // Will change both x.age and person.age
Object.create()
Метод Object.create() создаёт новый объект с указанным прототипом и свойствами.
Синтаксис
Object.create(proto[, propertiesObject])
Параметры
Объект, который станет прототипом вновь созданного объекта.
Необязательный параметр. Если указан и не равен undefined , должен быть объектом, чьи собственные перечисляемые свойства (то есть такие, которые определены на самом объекте, а не унаследованы по цепочке прототипов) указывают дескрипторы свойств, добавляемых в новый объект. Имена добавляемых свойств совпадают с именами свойств в этом объекте. Эти свойства соответствуют второму аргументу метода Object.defineProperties() .
Возвращаемые значения
Новый объект с заданным прототипом и свойствами
Выбрасываемые исключения
Выбрасывает исключение TypeError , если параметр proto не является null или объектом (исключение составляют объекты-обёртки примитивных типов).
Примеры
Пример: классическое наследование с Object.create()
Ниже показан пример использования Object.create() для имитации классического наследования. Это пример одиночного наследования, поскольку только его поддерживает JavaScript.
// Shape — суперкласс function Shape() this.x = 0; this.y = 0; > // метод суперкласса Shape.prototype.move = function(x, y) this.x += x; this.y += y; console.info('Фигура переместилась.'); >; // Rectangle — подкласс function Rectangle() Shape.call(this); // вызываем конструктор суперкласса > // подкласс расширяет суперкласс Rectangle.prototype = Object.create(Shape.prototype); Rectangle.prototype.constructor = Rectangle; var rect = new Rectangle(); console.log('Является ли rect экземпляром Rectangle? ' + (rect instanceof Rectangle)); // true console.log('Является ли rect экземпляром Shape? ' + (rect instanceof Shape)); // true rect.move(1, 1); // выведет 'Фигура переместилась.'
Если вы хотите наследоваться от нескольких объектов, то это возможно сделать при помощи примесей.
function MyClass() SuperClass.call(this); OtherSuperClass.call(this); > MyClass.prototype = Object.create(SuperClass.prototype); // наследование mixin(MyClass.prototype, OtherSuperClass.prototype); // примешивание MyClass.prototype.myMethod = function() // что-то делаем >;
Функция примешивания должна копировать функции из прототипа суперкласса в прототип подкласса, она должна предоставляться пользователем. Примером примеси может служить функция jQuery.extend().
Пример: использование аргумента propertiesObject с Object.create()
var o; // создаём объект с нулевым прототипом o = Object.create(null); o = >; // эквивалентно этому: o = Object.create(Object.prototype); // В этом примере мы создаём объект с несколькими свойствами. // (Обратите внимание, что второй параметр отображает ключи на *дескрипторы свойств*.) o = Object.create(Object.prototype, // foo является рядовым 'свойством-значением' foo: writable: true, configurable: true, value: 'привет' >, // bar является свойством с геттером и сеттером (свойством доступа) bar: configurable: false, get: function() return 10; >, set: function(value) console.log('Установка `o.bar` в', value); > /* при использовании методов доступа ES5 наш код мог бы выглядеть так: get function() < return 10; >, set function(value) < console.log('Установка `o.bar` в', value); >*/ > >); function Constructor() > o = new Constructor(); // эквивалентно этому: o = Object.create(Constructor.prototype); // Конечно, если бы в функции Constructor был бы реальный код инициализации, // метод с Object.create() не был бы эквивалентным // создаём новый объект, чей прототип является новым пустым объектом // и добавляем простое свойство 'p' со значением 42 o = Object.create(>, p: value: 42 > >); // по умолчанию свойства НЕ ЯВЛЯЮТСЯ записываемыми, перечисляемыми или настраиваемыми: o.p = 24; o.p; // 42 o.q = 12; for (var prop in o) console.log(prop); > // 'q' delete o.p; // false // для определения свойства ES3 o2 = Object.create(>, p: value: 42, writable: true, enumerable: true, configurable: true > >);
Полифил
Для этого полифила необходима правильно работающая Object.prototype.hasOwnProperty.
if (typeof Object.create != 'function') // Этапы производства ECMA-262, издание 5, 15.2.3.5 // Ссылка: http://es5.github.io/#x15.2.3.5 Object.create = (function() // Чтобы сэкономить память, используйте общий конструктор function Temp() > // делает безопасную ссылку на Object.prototype.hasOwnProperty var hasOwn = Object.prototype.hasOwnProperty; return function (O) // 1. Если Type(O) не является Object or Null выдаётся исключение TypeError. if (typeof O != 'object') throw TypeError('Object prototype may only be an Object or null'); > // 2. Пусть obj будет результатом создания нового объекта, как если бы // выражение new Object(), где Object является стандартным встроенным // конструктором с таким именем // 3. Установите для внутреннего свойства [[Prototype]] объекта obj значение O. Temp.prototype = O; var obj = new Temp(); Temp.prototype = null; // Давайте не будем держать случайные ссылки на О. // 4. Если аргумент Properties присутствует и не определён, добавляем // собственные свойства к obj, как будто вызывая стандартную встроенную // функцию Object.defineProperties с аргументами obj и // Properties. if (arguments.length > 1) // Object.defineProperties делает ToObject своим первым аргументом. var Properties = Object(arguments[1]); for (var prop in Properties) if (hasOwn.call(Properties, prop)) obj[prop] = Properties[prop]; > > > // 5. Возвращает obj return obj; >; >)(); >
Спецификации
Совместимость с браузерами
BCD tables only load in the browser