Reputation: 2495
I am a newbie in JavaScript and so don't really understand its object model, but as I understood I have to do something like.
function set_test(text) { this['test'] = text; };
a = {};
text = 'ok';
a.prototype.ok = set_test(text);
alert(a['test']); #Should be 'ok'
text = 'fail';
a.ok;
alert(a['test']); #Should be 'ok'
Can somebody say what's wrong here?
Upvotes: 0
Views: 143
Reputation: 8368
I think the whole code is wrong.
You see, in JavaScript, functions are objects and you can pass them around as you wish. The execution context (this
) depends on the way you invoke a function.
If you store a function in a property of an object and then invoke it by calling obj.fn()
, the execution context is set to obj
.
Also notice that you aren't supposed to invoke the function when assigning it as the object's property.
function set_test(text) { this['test'] = text; }
var a = {};
a.ok = set_test; // see, no invocation
a.ok('abc');
alert(a['test']); // alerts 'abc'
a.ok('def');
alert(a['test']); // alerts 'def'
Upvotes: 1
Reputation: 19609
Objects don't have a prototype by default, and a.prototype.ok = set_test(text);
would make ok
equal to the return value of set_test()
which is undefined
.
Try doing it this way instead:
function set_test(text) { this['test'] = text; };
var a = {
ok: set_test
},
text = 'ok';
a.ok(text);
alert(a['test']); //Should be 'ok'
text = 'fail';
a.ok(text);
alert(a['test']); //Should be 'fail'
Upvotes: 1
Reputation: 89
I think in function set_test this['test'] will not work. beacause "this" is not "a". You should define method set_test under object a - then it will work.
I recomend you check Mootools docs - there is much better object model syntax. You can also check Mootools source to get more detail answer to you question and js object model
Upvotes: 0