Home > Back-end >  Object with 2 methods. Method A, Method B. Calling Method B from within Method A
Object with 2 methods. Method A, Method B. Calling Method B from within Method A

Time:09-23

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?

CodePudding user response:

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

  • Related