I have written a constuctor
function Human() {
var legs = 2;
var iq = 100;
}
Then I create an instance of the object
var Man = new Human();
And want to add a new method
Man.getIQ = function() {
return iq - 10;
}
But I’m told that IQ is undefined. Even if I use this.iq.
Why isn’t a var inside the scope of an object available for new methods?
The variables
legsandiqare simulating a “private” member to theHumanclass because they are visible only in that closure (only in the Human function).If you want to access them from outside that scope, you need to make them public by binding them to the
thiskeyword (this.iq=100;) or by implementing getters and setters for each of your private member :Anyway, these are represent just the very tip of the iceberg; I explained them so that you can understand why what you were trying to do failed.
If I understand correctly what you were trying to do, the right way to write your ideea oop in js would be something like this :
Sorry if I got carried away, but there are lots of articles & blogs about javascript oop (such as this one) that I recommend you read before/while getting stuck with these kind of problems.