Plz help in this code


#1

I was reading MDN and came across an example which demonstrated the applications of ‘this’ keyword. It was about that the behavior is not at all affected by how or where the function was defined.

var o = {prop: 37};

function independent() {
  return this.prop;
}

o.f = independent;

console.log(o.f()); // 37

Similarly, the ‘this’ binding is only affected by the most immediate member reference. In the following example, when we invoke the function, we call it as a method g of the object o.b. This time during execution, this inside the function will refer to o.b. The fact that the object is itself a member of o has no consequence; the most immediate reference is all that matters.

o.b = {g: independent, prop: 42};
console.log(o.b.g()); // 42

So I was experimenting with this code in CodePen and I wrote the following code but it doesn’t show any error and shows nothing in the console. I think it should print out ‘42’ but I cannot find out what’s wrong.

var o = {
  prop: 37,
  f: function() { 
    return this.prop
  },
  b: { g: o.f, prop: 42}      
}

console.log(o.b.g())


#2

this can be used to access properties of an object within a method.

so here:

var o = {prop: 37};

function independent() {
  return this.prop;
}

o.f = independent;

console.log(o.f()); // 37

we make an object o, which we give a property named prop. Then later, we add a function to the object, thus the function becomes a method (methods are also properties of objects), which is why this keyword is working correctly

given we are still defining o, you can’t do o.f, to achieve this you need:

var o = {
  prop: 37,
  f: function() { 
    return this.prop
  }
}
o.b = { g: o.f, prop: 42}     

now we defined o, so we can actually use it


#3

I’m sorry I didn’t know this and I’m not clear how this works…

This works:

var o = {
  prop: 37,
  f: function() { 
    return this.prop
  }
}
o.b = { g: o.f, prop: 42} 

console.log(o.b.g()) 

But this doesn’t:

var o = {
  prop: 37,
  f: function() { 
    return this.prop
  },
  b: { g: o.f, prop: 42} 
}

console.log(o.b.g())

Why??? Because I can’t use o.f until o is fully defined?

I wanted b to already be a property of the object and then call the outer method inside the object b.


#4

yes, o isn’t defined yet, we are still in the process of defining o. So we can’t use it just yet.

this is possible, but then g needs to be a method, given methods execute when called. So they can have undefined values for the time being

see here:

https://stackoverflow.com/questions/4892221/i-need-to-call-a-parent-property-from-child-object-in-an-object-literal


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.