Harry
Harry

Reputation: 54989

javascript pass arguments into sibling object

I have something like this:

function showFunction () {
  // need position and place
}

var obj = {
  position: 1,
  place: 2,
  onShow: showFunction
}

How do I access position and place from showFunction?

Upvotes: 1

Views: 210

Answers (3)

Salman Arshad
Salman Arshad

Reputation: 272306

this should work:

When a function is called as a method of an object, its this is set to the object the method is called on.

function showFunction() {
    console.log(this.position, this.place);
}
var obj = {
    position: 1,
    place: 2,
    onShow: showFunction
}
obj.onShow()

Upvotes: 4

zzzzBov
zzzzBov

Reputation: 179216

Because you're making showFunction a member of obj, you can access the object via this.

function showFunction () {
    var a, b;
    a = this.position;
    b = this.place;
}

var obj = {
  position: 1,
  place: 2,
  onShow: showFunction
}

Alternatively, you could access obj just like you would outside of the function:

function showFunction () {
    var a, b;
    a = obj.position;
    b = obj.place;
}

Upvotes: 2

David G
David G

Reputation: 96845

Since functions are hoisted in JavaScript, you simply refer to .position and .place inside the function as you would outside the function:

function showFunction() {
  return obj.position;
}

But if for some reason you can't access obj, you can, as Jonathan said, pass obj as an argument to showFunction().

function showFunction(obj) {
    return obj.position;
}

var obj = {
  position: 1,
  place: 2,
  onShow: function() {
      return showFunction(obj);
  }
}

Upvotes: 2

Related Questions