Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access object property from object method in javascript

Tags:

javascript

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

like image 941
Nat Avatar asked May 10 '26 05:05

Nat


2 Answers

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();
like image 133
i100 Avatar answered May 12 '26 20:05

i100


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
like image 26
Carson Avatar answered May 12 '26 19:05

Carson