2

I was trying the below commands on Chrome console. I am able to create the object using new(line 2 below) but using call doesn't work. Can anyone explain what could be the reason ?

function ObjConstructor(){ this.sample = 1};

let withNew = new ObjConstructor();

let usingCall = ObjConstructor.call({});

usingCall
undefined  //output that came on console, this is not a command

withNew
ObjConstructor {sample: 1} //output that came on console
1
  • Great Inputs Quentin, T.J.C, ".call" works smoothly when we use it with "this" while setting up inheritance because this is Object and new properties are added to it and no need to return anything ;) Commented Mar 15, 2019 at 11:16

3 Answers 3

3

new does several things including:

  • Creating an object
  • Setting the this value to that object
  • Causes the function to return that object by default

Your code:

  • Creates an object manually with {}
  • Sets the this value to that object with call()

… but doesn't do the last thing. There is no return statement in the function, so it returns undefined.

Sign up to request clarification or add additional context in comments.

Comments

3

The result of call is whatever the function returns. Your ObjConstructor doesn't return anything, so the result of calling it is undefined.

In contrast, when you use new, a new object is created and passed to the function, and unless the function returns a non-null object, the object created for new is the result of the new expression.

That's why the new version works but the call doesn't.

Also note that call doesn't create an object at all. In your ObjConstructor.call({}), what creates the object is {}, not call. It won't have ObjConstructor.prototype as its prototype. ({} is a raw object initializer, so the object will have Object.prototype as its prototype.)

Comments

0

try this. Or look at this -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

var MyType = function(_param1,_param2){
this.param1 = _param1;
this.param2 = _param2;

this.ShowParam = function(){
  alert(this.param1+" - "+this.param2);
  }
}

var test = new MyType("PARAM TEST 1","PARAM TEST 2");

alert(test.param1+" - "+test.param2);


var test2 = new MyType("PARAM TEST 1.2","PARAM TEST 2.2");

alert(test2.param1+" - "+test2.param2);

test.ShowParam();
test2.ShowParam();

 

1 Comment

Thanks for inputs, I know about the Object but I want to learn of other alternatives to create Object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.