1

Say I have two methods on an Object.

Object = {
    MethodA() {
        console.log('A')
    },

    MethodB() {
        this.MethodA()
    }
}

The MethodA doesn't get called. why is this and how can I learn more about what I am doing wrong. What is the terminology called and where is this explained in the ECMA standard?

Greg Iven
  • 171
  • 2
  • 10
  • it seems like you might be interested in the concept of getters and setters: https://stackoverflow.com/questions/4616202/self-references-in-object-literals-initializers – imjared Sep 22 '21 at 13:54
  • It was more about calling a function from within a function, where they are both defined within the same object. Why does calling 'MethodA()' inside of MethodB() not work. Do methods in javascript not have access to the name space of the object? – Greg Iven Sep 22 '21 at 20:09

1 Answers1

0

Because this will be determined by the context in which the method is called and will not always refer to the object.

const object  = {
    MethodA() {
        console.log('this in A: ', this === window ? 'window' : this)
    },

    MethodB() {
        console.log('this in B: ', this === window ? 'window' : this)
        object.MethodA()
    }
}

object.MethodB() // this in B === object

const b = object.MethodB;

b() // this in B === window
pilchard
  • 12,414
  • 5
  • 11
  • 23