Can access an attribute of my object but not a function
I need to figure out how to develop oop-javascript correctly. I read a lot about prototypes
, but the internet explained to me, I only need this if I create an object many times. But mine SuperInterface
only exists 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();
The launch init()
succeeds title
on the console. But the warning is never called. I don't understand why not? What should I change?
source to share
The value this
in the middle of an object initializer is not a reference to an object under development. There is no way to get such a reference during initialization because the object does not exist yet and you are not referencing it with this
. So you really can't initialize a property like this. However, you can split it 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;
source to share
If you debug this code, you will find SuperInterface.actions[0].do_this
is undefined
The reason is quite obvious. During code evaluation.
actions: [{
title: 'This is great',
do_this: this.superaction
}]
this.superaction, here this
points to the window object.
and in this window, object exception does not exit.
To do this job you need
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 an answer. Thanks to
source to share
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 a literal object inside an array actions
- it does not contain a method superaction
.
source to share