Reputation: 12694
I have a chart object, with methods draw
and update
. See this (non-working) fiddle.
draw
does a lot of things with the object's properties, and at the end, draws a chart. At this point, I am able to define an update
function, since all the data that was processed by draw
is there. But then I can't call update
from outside the scope.
How do I define the update
method as a completely separate method so I can call it from outside the object, but have it be able to reference data within the draw
method?
Update: I've posted some semi-pseudo code.
Upvotes: 0
Views: 85
Reputation: 838
You can do something like:
var TestObject = function () {
var a, b;
this.draw = function (aVal, bVal) {
a = aVal;
b = bVal;
}
this.update = function () {
console.info("a = " + a + " | b = " + b);
}
}
Then you can call as:
var obj = new TestObject();
obj.draw(3, 4);
obj.update();
jsfiddle at - http://jsfiddle.net/poonia/XAm52/
Upvotes: 0
Reputation: 136104
like this perhaps:
function MyChart(x,y){
this.draw = function(){
console.log('draw chart using variables x:' + x + ' y:' + y);
return {
update: function(){
console.log('update chart using variables x:' + x + ' y:' + y);
}
}
}
}
usage:
var chart = new MyChart(123,987);
var drawResult = chart.draw();
drawResult.update();
Live example: http://jsfiddle.net/c9TeU/
Upvotes: 3
Reputation: 37137
Since you don't give us much information I'll try to guess what you want. I assume you want this:
var updateFunction = function(){
update();
};
return updateFunction();
But you can just directly return update;
In javascript functions can be stored in variables, so if you can pass a variable to outside the scope you can also pass a function
Upvotes: 0
Reputation: 60727
function update(obj) {
}
var obj = {
function draw() {
update(this); // works
}
};
You might want to read about Javascript Functions and function scope, and about lexical scope.
Upvotes: 1