Reputation: 85
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/
Upvotes: 7
Views: 96
Reputation: 9066
"THIS " inside a method of constructor function always indicate the instance of that constructor function ,in your case this==farm.You are passing the whole object instance inside getElementById()
method.Change your printCost method to get the name of the object instance which matches this.You need to iterate over window object which will have all the variables defined in it's scope.So your object will be to get the variable name from window object which matches the name of the name of the variable "farm". Then use it in getElementById()
.check this answer for more detail
this.printCost = function(){
for(var prop in window){
if(window[prop]==this){
document.getElementById(prop).innerHTML = this.cost;
}
}
}
Upvotes: 2
Reputation: 57964
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
.
Upvotes: 4
Reputation: 1633
You have to assign this to variable, and use it on your anonymous
function
var Building = function(cost){
this.cost = cost;
var currentObj = this;
this.printCost = function(){
document.getElementById(this).innerHTML = currentObj.cost;
}
}
var farm = new Building (50);
farm.printCost();
Upvotes: -4