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/
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With