Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function changing the "this" variable

I'm new to JavaScript and trying to get my head around some of the fundamentals of OOP and simulated "classes".

Upon executing the final line of this script, I would like the invoked this object pointer on line 4 to refer to the farm object (just like it correctly does in line 2 and 3).

Unfortunately it does not, and I would guess that the this object pointer is instead pointing towards document.

var Building = function(cost){
    this.cost = cost;
    this.printCost = function(){
        document.getElementById(this).innerHTML = this.cost;
    }
}

var farm = new Building (50);

farm.printCost();

-

<html>
<body>
<p id="farm">
</p>
</body>
</html>

Is there a way to get this function to use right object? If there are any errors in my understanding please let me know.

I'm not yet familiar with jQuery so if you could stick to core JavaScript syntax I'd appreciate it!

JSFiddle: https://jsfiddle.net/7n2of9k7/

like image 711
Rilke Avatar asked Sep 07 '16 03:09

Rilke


1 Answers

As far as I know, getting the instance's variable name as a string is impossible. I also really don't see why you would would do this as it's quite impractical. I would just pass in the element you want inserted into as a string:

var Building = function(cost, element){
    this.cost = cost;
    this.printCost = function(){
        document.getElementById(element).innerHTML = this.cost;
    }
}

var farm = new Building(50, 'farm');

farm.printCost();
<p id="farm">
</p>

This now just passes an ID into the function so it inserts correctly. You can also pass this to printCost.

like image 135
Andrew Li Avatar answered Oct 06 '22 00:10

Andrew Li