Suppose I have a Javascript object (the curly braces indicate it is so):
{
a: function (something) {
return something*2;
},
b: function () {
var c = this.a(2); //Does not work. Why?
return c;
}
}
What is the workaround to this?
2 Answers 2
It not work because when you access the method b it context isn't the instance from object that you made, it will try to search in the binded context or in window object.
var x = {
a: function (something) {
return something*2;
},
b: function () {
var c = x.a(2); //Does not work. Why?
return c;
}
}
This way you are using the x as context to access the method a.
Or you can use a new operator to create your object and the method as it prototype or direct method.
When you do it, the result will be:
var x = function() {
return {
a: function (something) {
return something*2;
},
b: function () {
var c = this.a(2); //Does not work. Why?
return c;
}
}
}
It will make you lose the prototype from x, when you make a new instance, but your code will work.
Example:
var y = new x();
console.log(y.b());
2 Comments
x = was implied on the question. If not, how could the OP possibly be calling b?x is inside b method context. I did just put there for an example of use. This way you cant make it won't work using x.b.apply(window); for example.It works for me, you were missing a coma after a declaration.
{
a: function (something) {
return something*2;
}, // -> this one
b: function () {
var c = this.a(2);
return c;
}
}
If you call b the function should return a(2) which is 2*2=4
alert(p.b());
b?thisis entirely dependent on how you are callingb()and cannot be answered otherwise.not a real question.