Javascript create object with arguments

new operator

The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

Try it

Syntax

new constructor new constructor() new constructor(arg1) new constructor(arg1, arg2) new constructor(arg1, arg2, /* …, */ argN) 

Parameters

A class or function that specifies the type of the object instance.

A list of values that the constructor will be called with. new Foo is equivalent to new Foo() , i.e. if no argument list is specified, Foo is called without arguments.

Description

When a function is called with the new keyword, the function will be used as a constructor. new will do the following things:

  1. Creates a blank, plain JavaScript object. For convenience, let’s call it newInstance .
  2. Points newInstance ‘s [[Prototype]] to the constructor function’s prototype property, if the prototype is an Object . Otherwise, newInstance stays as a plain object with Object.prototype as its [[Prototype]].

Note: Properties/objects added to the constructor function’s prototype property are therefore accessible to all instances created from the constructor function.

Classes can only be instantiated with the new operator — attempting to call a class without new will throw a TypeError .

Creating an object with a user-defined constructor function requires two steps:

    Define the object type by writing a function that specifies its name and properties. For example, a constructor function to create an object Foo might look like this:

function Foo(bar1, bar2)  this.bar1 = bar1; this.bar2 = bar2; > 
const myFoo = new Foo("Bar 1", 2021); 

Note: An object can have a property that is itself another object. See the examples below.

You can always add a property to a previously defined object instance. For example, the statement car1.color = «black» adds a property color to car1 , and assigns it a value of «black» .

However, this does not affect any other objects. To add the new property to all objects of the same type, you must add the property to the constructor’s prototype property. This defines a property that is shared by all objects created with that function, rather than by just one instance of the object type. The following code adds a color property with value «original color» to all objects of type Car , and then overwrites that value with the string «black» only in the instance object car1 . For more information, see prototype.

function Car() > const car1 = new Car(); const car2 = new Car(); console.log(car1.color); // undefined Car.prototype.color = "original color"; console.log(car1.color); // 'original color' car1.color = "black"; console.log(car1.color); // 'black' console.log(Object.getPrototypeOf(car1).color); // 'original color' console.log(Object.getPrototypeOf(car2).color); // 'original color' console.log(car1.color); // 'black' console.log(car2.color); // 'original color' 

Note: While the constructor function can be invoked like any regular function (i.e. without the new operator), in this case a new object is not created and the value of this is also different.

A function can know whether it is invoked with new by checking new.target . new.target is only undefined when the function is invoked without new . For example, you can have a function that behaves differently when it’s called versus when it’s constructed:

function Car(color)  if (!new.target)  // Called as function. return `$color> car`; > // Called with new. this.color = color; > const a = Car("red"); // a is "red car" const b = new Car("red"); // b is `Car < color: "red" >` 

Prior to ES6, which introduced classes, most JavaScript built-ins are both callable and constructible, although many of them exhibit different behaviors. To name a few:

  • Array() , Error() , and Function() behave the same when called as a function or a constructor.
  • Boolean() , Number() , and String() coerce their argument to the respective primitive type when called, and return wrapper objects when constructed.
  • Date() returns a string representing the current date when called, equivalent to new Date().toString() .

After ES6, the language is stricter about which are constructors and which are functions. For example:

  • Symbol() and BigInt() can only be called without new . Attempting to construct them will throw a TypeError .
  • Proxy and Map can only be constructed with new . Attempting to call them will throw a TypeError .

Examples

Object type and object instance

Suppose you want to create an object type for cars. You want this type of object to be called Car , and you want it to have properties for make, model, and year. To do this, you would write the following function:

function Car(make, model, year)  this.make = make; this.model = model; this.year = year; > 

Now you can create an object called myCar as follows:

const myCar = new Car("Eagle", "Talon TSi", 1993); 

This statement creates myCar and assigns it the specified values for its properties. Then the value of myCar.make is the string «Eagle», myCar.year is the integer 1993, and so on.

You can create any number of car objects by calls to new . For example:

const kensCar = new Car("Nissan", "300ZX", 1992); 

Object property that is itself another object

Suppose you define an object called Person as follows:

function Person(name, age, sex)  this.name = name; this.age = age; this.sex = sex; > 

And then instantiate two new Person objects as follows:

const rand = new Person("Rand McNally", 33, "M"); const ken = new Person("Ken Jones", 39, "M"); 

Then you can rewrite the definition of Car to include an owner property that takes a Person object, as follows:

function Car(make, model, year, owner)  this.make = make; this.model = model; this.year = year; this.owner = owner; > 

To instantiate the new objects, you then use the following:

const car1 = new Car("Eagle", "Talon TSi", 1993, rand); const car2 = new Car("Nissan", "300ZX", 1992, ken); 

Instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects rand and ken as the parameters for the owners. To find out the name of the owner of car2 , you can access the following property:

Using new with classes

class Person  constructor(name)  this.name = name; > greet()  console.log(`Hello, my name is $this.name>`); > > const p = new Person("Caroline"); p.greet(); // Hello, my name is Caroline 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Feb 21, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

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

Смотрите также

Источник

Читайте также:  Тег big в html
Оцените статью