Home > Software engineering >  Javascript: How to apply properties from two different objects to a new object?
Javascript: How to apply properties from two different objects to a new object?

Time:01-20

Why does this code output "0" instead of "2"?

I'm new to Javascript, and quite new to programming in general. I'm making a game in javascript to learn.

As you might understand from the code, I want to have one function that allows me to create new game objects that contains some common properties (e.g. weight), and some additional properties by naming the specific kind of game object as an argument. Thanks a lot in advance!

function brick() {
 return {
  length: 2,
  width: 4,
};
}


//Constructor function for new game objects
function GameObject(positionX, positionY, gameObjectType = {}) {
this.weight = 2;
this.positionX = 1;
this.positionY = 2;
this.length = gameObjectType.length;
this.width = gameObjectType.width;
}

//Creating a new game object as a test
let example = new GameObject (4, 6, brick); 

console.log(example.length);

CodePudding user response:

Brick is a function, I think you need to do let example = new GameObject (4, 6, brick());

CodePudding user response:

It's because you just pass the brik function and you don't call it.

Your code must kile this:

let example = new GameObject (4, 6, brick());

With this you will be able to recive { length: 2, width: 4, }; from your function and your code will work currectly

  • Related