如何在对象中传递数据?

时间:2013-01-25 08:55:16

标签: javascript oop d3.js

我有一个图表对象,方法drawupdateSee this (non-working) fiddle

draw使用对象的属性做了很多事情,最后绘制了一个图表。此时,我能够定义update函数,因为draw处理的所有数据都在那里。但是我不能在范围之外调用update

如何将update方法定义为一个完全独立的方法,以便我可以从对象外部调用它,但是它能够在draw方法中引用数据吗?

更新:I've posted some semi-pseudo code

4 个答案:

答案 0 :(得分:3)

或许这样:

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);
          }
      }
   }
}

用法:

 var chart = new MyChart(123,987);
 var drawResult = chart.draw();
 drawResult.update();

实例:http://jsfiddle.net/c9TeU/

答案 1 :(得分:1)

function update(obj) {
}

var obj = {
    function draw() {
        update(this); // works
    }
};

您可能希望阅读有关Javascript Functions and function scopelexical scope

的信息

答案 2 :(得分:0)

由于你没有给我们太多信息,我会试着猜你想要什么。我想你想要这个:

var updateFunction = function(){
   update();
};

return updateFunction();

但你可以直接return update;在javascript函数中可以存储变量,所以如果你可以将一个变量传递到范围之外你也可以传递一个函数

答案 3 :(得分:0)

您可以执行以下操作:

var TestObject = function () {
    var a, b;
    this.draw = function (aVal, bVal) {
        a = aVal;
        b = bVal;
    }
    this.update = function () {
        console.info("a = " + a + " | b = " + b);
    }
}

然后你可以打电话给:

var obj = new TestObject();
obj.draw(3, 4);
obj.update();

jsfiddle at - http://jsfiddle.net/poonia/XAm52/

相关问题