I'm confused with the this keyword in javascript, I want to know if I can do what I intended?

59 views Asked by At

This code works fine, although what I'm interested in knowing is, if there's a way that works better and is which I prefer better, which it seem to not be working. Is it possible to do it that way, check the second code example in order to comprehend, what I have in mind when I say "preferred way".

code 1

function a(y){this.b=y;};
var ax = new a("oka");
alert(ax.b);

code 2 (preferred way but does not work)

function a(){this.b = alert(y);this.y = y;}
var ax = new a();
ax.y="okay";
ax.b;
2

There are 2 answers

0
T.J. Crowder On BEST ANSWER

Your use of this is mostly fine, but the problem is that this line:

this.b = alert(y);

...calls alert and assigns its return value to b. If you wanted b to be a function, you'd do:

this.b = function() {
    alert(this.y);        // Note `this`
};

...so:

function a() {
    this.b = function() {
        alert(this.y);
    };
}
var ax = new a();
ax.y = "okay";
ax.b();                   // Note the ()

Side note: The overwhelming convention in JavaScript is to give constructor functions (functions you call via new) names starting with a capital letter. So A rather than a, for instance.

0
Zack On

If you want to assign a function to the this.b property, you can do it like so:

// Declare the a variable.
var a = {};
// Set the a.b property.
a.b = function(){alert('hi');}
// Call the function set on a.b.
a.b();