No, it's not acceptable, since this code will easily break your "fix":
Test.prototype.myIncrement = function() {
return this.increment();
};
This is defined in the prototype, and thus it can access this.increment
. JavaScript allows prototypes to be modified at runtime, and prototypes edits are shared among all instances of the object.
//Test "class"
var t1 = new Test(1);
Test.prototype.myIncrement = function() {
return this.increment();
};
console.log(t1.getCounter());
console.log(t1.getNext());
console.log(t1.myIncrement());
console.log(t1.getCounter());
Remember that JavaScript is executed on the client machine, so it can be modified as the owner prefers. You can make it harder to someone to modify your code, but it is never impossible.
Sidenote:
I suppose that looping on object prototype for each call could be expensive (use of hash table instead?) and I know that use of arguments.callee.caller is deprecated (and break the inlining in js compiler).
Yes, it could be extremely expensive, but in this case(since the prototype is small) the true problem is arguments.caller.callee
. This is what is causing your performance issues.
One last thing, when looping with a for..in
operator remember to use hasOwnProperty
, or you could have unexpected results.