Top community members

In the past we had a dream,
to have place where we could share IT knowledge,
to ask questions without fear that someone will judge us.

Now we are a group of people who make this dream come true. ❀ đŸ’»

If you think sharing knowledge and helping other is valuable.

join our community - Click here

[Edit]
EN

JavaScript - how to use '.call(...)' method with (or instead) 'new' operator

5 points
Created by:
JustMike
3364

In this article we would like to show how to create object with MyClass.call(...) method instead of new operator in JavaScript.

Simple solution:

// ONLINE-RUNNER:browser;

function MyClass(a, b) {
	console.log(a + ' ' + b);
	this.print = function(c, d) {
		console.log(a + ' ' + b + ' -> ' + c + ' ' + d);
	};
}

var object = { };
MyClass.call(object, 'a', 'b');

object.print('c', 'd');

Note: read this article to see MyClass.apply(...) method examples.

Check below alternative solutions:

Alternative solutions

There are few different ways how to achieve same effect, what was presenbted in this section.

new operator with .bind.call(...) methods example

// ONLINE-RUNNER:browser;

function MyClass(a, b) {
	console.log(a + ' ' + b);
	this.print = function(c, d) {
		console.log(a + ' ' + b + ' -> ' + c + ' ' + d);
	};
}

var object = new (MyClass.bind.call(MyClass, null, 'a', 'b'));
object.print('c', 'd');

new operator, .bind.call(...) methods with Function class example

// ONLINE-RUNNER:browser;

function MyClass(a, b) {
	console.log(a + ' ' + b);
	this.print = function(c, d) {
		console.log(a + ' ' + b + ' -> ' + c + ' ' + d);
	};
}

var object = new (Function.prototype.bind.call(MyClass, null, 'a', 'b'));
object.print('c', 'd');

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more