I have a basic lack in understanding the OOP for javascript. What I understand is that I can make classes like this
var Car = function(){}
Car.prototype.GetBrand = function(){ return "Ford";}
Car.prototype.GetYear = function(){ return "1989";}
var ford = new Car();
ford.GetBrand();
ford.GetYear();
this works…
Now I want to implement a function GetInfo and this should print out Brand & Date
how can I reference the GetBrand() and GetYear() methods in my GetInfo() method.
This is not working:
Car.prototype.GetInfo = function(){
return this.GetBrand()+ ' '+ this.GetYear();
}
this is not the right accessor…
What do I miss here?
OK edit:
this was a simplified example there my realy method call is in anothe function and that’s why we are talking about another scope:
JsonLoader.prototype.GetJsonAndMerge = function(url,template,tagToAppend){
$.ajax({
url: url,
dataType: 'json',
success: function(data) {
this.ShowItems(data,template,tagToAppend);
}
});
}
I try to reach my ShowItems method… here and this is again in a function that’s maybe why the this operator does not work… sorry for the confusion =/
You are missing an unintended recursion:
Then you can call
EDIT: The reason to use
prototypehere is to conserve memory. When you callnew Car(), the object gets copied, not “constructed” in the traditional sense. Callingnewonwould also copy the function bodies to every instance. This is why putting a method into the prototype chain makes sense. Also adding a function to already-existing instances only works when adding it to the prototype chain.
Also note that the convention is to give capital first letters to constructor functions only, so
Caris okay, butGetInfoshould begetInfo.