Reputation: 6079
I have to figure out, how to develop oop-javascript the right way. I read a lot about prototypes
but the internet explained to me, I need it only, if I create an object a lot of times. But my SuperInterface
exists only once. So I created it as an object:
var SuperInterface = {
superaction: function () {
alert(1);
},
actions: [{
title: 'This is great',
do_this: this.superaction
}],
init: function () {
console.log(this.actions[0].title);
this.actions[0].do_this();
}
};
SuperInterface.init();
Running init()
puts the title
successfully to the console. But the alert is never called. I do not understand, why not? What should I change?
Upvotes: 3
Views: 58
Reputation: 413737
The value of this
in the middle of that object initializer is not a reference to the object that is "under construction". There is no way to get such a reference during initialization since the object doesn't yet exist, and nor would you reference it with this
. So you really can't initialize a property like that. You can however split it out into a separate statement:
var SuperInterface = {
superaction: function () {
alert(1);
},
actions: [{
title: 'This is great',
do_this: null;
}],
init: function () {
console.log(this.actions[0].title);
this.actions[0].do_this();
}
};
SuperInterface.actions[0].do_this = SuperInterface.superaction;
Upvotes: 6
Reputation: 10538
var SuperInterface = {
superaction: function () {
alert(1);
},
actions: [{
title: 'This is great',
do_this: function() {
return SuperInterface.superaction();
}
}],
init: function () {
console.log(this.actions[0].title);
this.actions[0].do_this();
}
};
SuperInterface.init();
this
in your case refers to the literal object inside the array actions
- it does not contain the method superaction
.
Upvotes: 0
Reputation: 10827
If you debug this code, you will find SuperInterface.actions[0].do_this
is undefined
The reason is quite obvious. At the time of evaluation of code.
actions: [{
title: 'This is great',
do_this: this.superaction
}]
this.superaction, here this
points to the window object.
and in this window object superaction does'nt exits..
To make this work eventually you need to
var SuperInterface = {
superaction: function () {
alert(1);
},
actions: [{
title: 'This is great',
do_this: null
}],
init: function () {
console.log(this.actions[0].title);
this.actions[0].do_this();
}
};
SuperInterface.actions[0].do_this = SuperInterface.superaction;
SuperInterface.init();
I hope you got the answer. Thanks
Upvotes: 2