I am currently creating objects in javascript by declaring a construct (regular function) and then adding methods to the prototype, for example:
function Test(){ } Test.prototype.test1 = function(){ var me = this; }
However, I would like not to declare var me = this at the top of each function. The following seems to work, but it looks like it will be very inefficient:
$(document).ready(function(){ var n = 0; (function(){ function createTest(){ var me; function Test(){ this.n = n; this.testArr = [1, 2, 3, 4]; n++; } Test.prototype.test1 = function(){ me.test2(); }; Test.prototype.test2 = function(){ alert(me.n); $.getJSON('test.php', {}, function(reply) //want to be able to use 'me' here me.newField = reply; }); }; var t = new Test(); me = t; return t; } window['createTest'] = createTest; })(); var t = createTest(); t.test1(); var t2 = createTest(); t2.test1(); t.test1(); });
This code prints the expected, but is it really inefficient how it looks (the Test object is re-declared each time you call createTest ())?
Anyhoo, that would seem a bit hacked ... is there a completely different way to do this, which is better?
EDIT: The real reason I would like to do this is because callbacks like the ones in test2 would have references to the correct this .
source share