Reputation: 447
I have the following object:
dog = {
location: {
x: 52.1089,
y: 16.2323
},
f: function(message) {
alert(message + this.location.x);
return;
}
};
Now I need to start passing the function dog.f
to an API in different contexts. My problem is that this
not always refers to my object but to different things depending on how it is called. How can I access properties like location
inside the function f
?
EDIT: What I actually want is only the method f
but I dont want to initialize location inside f
on each function call, so I thought an object would be the best idea. This was my first attempt:
var f = function(message) {
var location: {
x: 52.1089,
y: 16.2323
}
alert(message + location.x);
return;
}
but it looks wasteful to initialiaze location on every function call.
EDIT 2: I am open for a coffeescript solution
Upvotes: 0
Views: 44
Reputation: 147343
You might consider using a closure (see Private Members in JavaScript):
var dog = (function() {
var location = {x: 52, y:16};
return {
getLocation: function() {
return [location.x, location.y];
},
setLocation: function (newX, newY) {
location.x = newX;
location.y = newY;
},
showMessage: function(message) {
alert(message + location.x);
}
};
}());
dog.showMessage('here : ');
Upvotes: 2
Reputation: 3330
You probably want to do this
var Dog = function() {
this.location = {
x: 52.1089,
y: 16.2323
};
this.f = function(message) {
alert(message + this.location.x);
return;
}
};
var dogObj = new Dog();
dogObj.f("Hellow World!");
Upvotes: 0
Reputation: 700152
You can use the bind
method to set the context for the method:
var func = dog.f.bind(dog);
When you call func
from anywhere, it will have the same context as if it was called as dog.f
.
Note: The bind
method isn't supported in older browsers, for example IE 8 and older, so you would need a 'polyfill' if you need to support those. There is one in the documentation that I linked to.
Upvotes: 4