9

I have something like

var foo = function(arg){
  var something = {
    myPropVal: "the code",
    myMethodProp: function(bla) {
      // do stuff with mypropval here
      alert(this) // => DOMWindow
    }
  }
}

is this possible? can i access the contents of myPropVal from within myMethodProp given the

0

4 Answers 4

9

sure you can

var foo = function(arg){
  var something = {
    myPropVal: "the code",
    myMethodProp: function(bla) {
      // do stuff with mypropval here
      alert(this) // => DOMWindow
      alert(this.myPropVal);
    }
  }

  alert(something.myMethodProp());
}
foo();
Sign up to request clarification or add additional context in comments.

2 Comments

So actually this is not the DOMWindow.
What this is depends on the context of how the function was invoked. So you might be safer using something explicitly.
8

Yes, you can, below is an example.

obj = {
  offset: 0,
  IncreaseOffset: function (num) {
    this.offset += num
  },
  
  /* Do not use the arrow function. Not working!
  IncreaseOffset2: (num) => {
    this.offset += num
  } 
  */
}

obj.IncreaseOffset(3)
console.log(obj.offset) // 3

1 Comment

This answer deserves some love. The arrow function, for whatever reason doesn't work in this case - excellent spot! ++1
3

In the context of an anonymous function used as property in an object, this refers to the object and can be used to access other properties.

const robin = {
  firstName: 'Robin',
  lastName: 'Wieruch',
  getFullName: function () {
    return this.firstName + ' ' + this.lastName;
  },
};

console.log(robin.getFullName());
// "Robin Wieruch"

Comments

2

You might have to reference it as something.myPropVal.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.