I am new to prototype, and I just made a simple example that won’t work. From the code below its obvious what I want – a counter. But for some reason the output is always 5, I guess that the bind is making a deep copy of the this object, which is then bound to the function. There is an obvious solution where I make everything public, but I would like to know if there is a more elegant solution. (Or you may correct my and tell me that there is no deep copy, but some other bug). The documentation didn’t help me.
The code:
<!DOCTYPE html>
<html>
<body>
<input type="button" value="click" onclick="javascript: doTest();" />
<div id="canvas"></div>
<script>
var ClassA = function (position, element) { // constructor
this.field1 = position;
this.target = element;
};
ClassA.prototype = function () {
// private functions
var _aPrivateMethod = function(){
console.log(this);
this.field1 += 1;
return this.field1;
};
var _aPublicMethod = function(){
this.target.innerHTML = _aPrivateMethod.bind(this)();
};
return { // interface
constructor: ClassA,
aPublicMethod : _aPublicMethod
};
}();
function doTest() {
var obj = new ClassA(4, document.getElementById('canvas'));
obj.aPublicMethod();
}
</script>
</body>
</html>
Here are a number of issues. First you call
doTesteach time. A new object is created on each click, so there’s no way to incrementfield1.As I understood you want
field1to be private. In the way you initialize it, it cant be private. You can do something like:In that way you can’t access the
counterfrom outside the function scope.Another issue is that you don’t call the private method with the right context. You should use
_aPrivateMethod.call(this)as pimvdb have mentioned.Here is an example of:
In that way
eatCake,incrementAgeandageare all private because of the functional scope.The bad thing in the example is the way I’ve declared the function
birthday. For each instance ofPersona new copy will be created.The right way is:
My declaration is not like this one because I want to use a private data members. Actually not private just local for the function (
age,eatCake,incrementAge).There’s no way to access them from a function which is declared in the prototype, so that’s why for the example above I’ve choose that approach.