Shivam Sinha Shivam Sinha - 6 months ago 15
Javascript Question

this keyword for object literal

Hi In the example below I am importing MeasurementObject using:

import MeasurementObject from './app/..etc'


When I call an instance of MeasurementObject.getScrollToValue()

The
this
inside the method
MeasurementObject.getScrollToValue()
refers to the executing context. As a result
this.getURL()
is undefined. How can I get it to to refer to the current context of MeasurementObject and hence call
this.getURL()
.

const MeasurementObject = {

getType(){
return "a"
}

getURL(){
return "b";
}

getScrollToValue(){
return this.getURL();
}
}

export default MeasurementObject;

Answer

when you export a class without instantiate it, all the properties you define are set on the prototype. and you dont have a context, you need to instantiate and you then are able to use "this".

Now as for your example the "this" inside your function referring to the object correctly however you are not returning it.

const MeasurementObject = {

    getType(){
        return "a"
    },

    getURL(){
        return "b";
    },

    getScrollToValue(){
        return this.getURL();
    }
}


var a = MeasurementObject.getScrollToValue()
console.log(a)

When you define an object like that your already working on an instance and the properties are set on the object not its prototype.

update

When you do this:

class MeasurementClass {

    getType(){
        return "a"
    },

    getURL(){
        return "b";
    },

    getScrollToValue(){
        return this.getURL();
    }
}

what you get is something like:

function MeasurementClass(){}
MeasurementClass.prototype.getType = function(){ return "a" }
MeasurementClass.prototype.getURL = function(){ return "b"; }
MeasurementClass.prototype.getScrollToValue = function(){ return     this.getURL(); }

And then when you try accessing it without instantiating MeasurementClass.getScrollToValue

You are trying to access something that doesn't exist.

However when you instantiate the function all of those prototype properties are inherited to the instance so:

const measurementClass = new MeasurementClass();

measurementClass will be an instance of MeasurementClass and will inherit all its prototype.

Hope that helps a little.

Comments