Home > Blockchain >  Can I access this of an object in JavaScript?
Can I access this of an object in JavaScript?

Time:01-04

var b = {
    state: 'initial',
    initial: {
        onClick: function() {
            console.log(this);
        },
        x: 0,
    },
}

Hi, I want to know if its possible to access b object inside onClick function in the code above?

the output is {x: 0, onClick: ƒ} instead of {state: 'initial', ... }

Changing it to arrow func will output window object instead.

Im making an escape room game and kind of have a chicken & egg situation.

var spriteObject =
{
  img: null,
  INITIAL: {
    sourceX: 0,
    sourceY: 0,
    sourceWidth: 64,
    sourceHeight: 64,
    x: 0,
    y: 0,
    width: 64,
    height: 64,
    isWithinBounds: function(x, y) {
      return x > this.x && x < this.x   this.width && y > this.y && y < this.y   this.height;
    },
  },
  
  state: 'INITIAL',
};
const inventoryItems = [];
let currentRoom = "kitchen";

const knife = {
  ...spriteObject,
  INITIAL: {
      ...spriteObject.INITIAL,
      x: 200,
      y: 162,
      sourceX: 1330,
      sourceY: 8,
      sourceWidth: 803,
      sourceHeight: 514,
      width: 803,
      height: 514,
      onClick: () => {
        inventoryItems.push(knife);
        layers.kitchen.sprites = layers.kitchen.sprites.filter(sprite => sprite !== knife);
      },
  },
  img: kitchenLayout,
};

const layers = {
  kitchen: {
    sprites: [knife],
  },
};

window.addEventListener("click", function(e) {
  const x = e.pageX - canvas.offsetLeft;
  const y = e.pageY - canvas.offsetTop;
  layers[currentRoom].sprites.forEach(sprite => {
    const currSprite = sprite[sprite.state];
    if (currSprite.onClick && currSprite.isWithinBounds(x, y)) {
      currSprite.onClick();
      render();
    }
  })
})

Let's say I have a kitchen room and a knife on the counter. I can pick the knife and put it in my inventory. The knife will have 3 different conditions: on the counter (initial), in inventory, and dull (after used). I am not sure if I want to model in inventory as a state, but I have trouble figuring out how to remove the knife from list of sprites in kitchen. It is doable in the code above but it seems to rely on the fact that I declare knife as a variable. I don't want to do this, in case I want to declare my items directly on the sprites array. I appreciate any hints, thanks

CodePudding user response:

You should be able to use javascript classes for this. That way you can reference your current class as this.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

  •  Tags:  
  • Related