-3

I'm confused as to why the code below will return undefined. If you console.log(this) you will get the myObj object and not the global window object. Therefore, 'this' is clearly pointing to the correct object to access the value of x and y yet it returns undefined. Here is the code:

var myObj = {
    takeTwoNums: function (x, y) {
        console.log(this.x);
    }
}
myObj.takeTwoNums(1, 2);
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
Haloor
  • 221
  • 4
  • 14

3 Answers3

8

In your call to takeTwoNums, this refers to the same object that myObj refers to. That object doesn't have an x property. It has a takeTwoNums property, and a couple of properties it inherits from Object.prototype like toString and such, but no x.

The x is an argument to the method. You just reference it as x. Calling the method doesn't make this refer to an object that has the arguments as properties.

You may be confusing this with something like this:

function Thingy(x) {
    this.x = x;
}

// Then
var t = new Thingy(42);

In that case, because we used new, it created a new object and then called Thingy with this referring to that new object and we created a property on it called x that we initialized with the value of the argument x. But that's another thing entirely than just calling a function.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    ok, that makes a lot of sense so the problem is I'm trying to access a variable that doesn't exist within the object construct because it is an argument that can only be passed in from outside the `myObj` object. Thus the variable must be defined within the object in order to use the 'this' keyword. Something like this: `var myObj = { x: 1, takeTwoNums: function () { console.log(this.x); }}myObj.takeTwoNums()` – Haloor Oct 11 '16 at 21:20
  • @Haloor: Right. At which point we call it a *property*, rather than a *variable* (or *argument*), but it's much the same thing. – T.J. Crowder Oct 11 '16 at 21:35
2

You don't need to use this. Instead, try this:

var myObj = {
    takeTwoNums: function (x, y) {
        console.log(x);
    }
}
myObj.takeTwoNums(1, 2);
Brandon
  • 3,074
  • 3
  • 27
  • 44
1

this is referring to the object, so by using this.x you're requesting the x of myObj. In other words, it's looking for myObj.x, which doesn't exist.

Here's a small reference guide for this in objects:

var myObj = {
    myVal: 3,
    takeTwoNums: function (x, y) {
        console.log(x);
    },
    takeThisNum: function (x, y) {
        console.log(this.x);
    },
    getVal: function() {
        console.log(myVal);
    },
    realGetVal: function() {
        console.log(this.myVal);
    }
}
myObj.takeTwoNums(1, 2); // Logs 1
myObj.takeThisNum(1, 2); // Logs undefined
myObj.getVal(); // Logs undefined
myObj.realGetVal(); // Logs 3
Quangdao Nguyen
  • 1,343
  • 11
  • 25