Какая разница между функцией и функцией-конструктором в javascript?

Какая разница между обычной функцией и функцией-конструктором? Когда функция считается функцией-конструктором?

Если объяснять простыми словами, то функция конструктор это функция позволяющая построить объект, в её теле зачастую используется ключевое слово this, а также для создания объекта мы можем написать следующее:

var a = new MyConstructor(prop1, prop2);

в данном случае MyConstructor - это функция конструктор, а prop1 и prop2 - значения свойств пол ученого объекта (внутри функции может написано следующее: this.prop1 = prop1;)

Для того, что бы лучше разобраться с функциями конструкторами нужно познакомиться с оператором new и его работой, для этого могу порекомендовать во эту статью: new - JavaScript | MDN

а так же вот вырезка из неё:

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.The new keyword does the following things:

Creates a blank, plain JavaScript object;

  1. Links (sets the constructor of) this object to another object;
  2. Passes the newly created object from Step 1 as the this context;
  3. Returns this if the function doesn't return its own object.

When the code new Foo(...) is executed, the following things happen:

  1. A new object is created, inheriting from Foo.prototype.
  2. The constructor function Foo is called with the specified arguments, and with this bound to the newly created object. new Foo is equivalent to new Foo(), i.e. if no argument list is specified, Foo is called without arguments.
  3. The object (not null, false, 3.1415 or other primitive types) returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)

Также нужно заметить, что функцию конструктор также можно вызывать как и обычною функцию (для этого ваш код работает не в строгом режиме), но тогда переменная, в которую будет записываться результат работы функции, будет иметь значение undefined.

1 Вподобання