2012-03-02 159 views
1

如何訪問「runit」和「property2」的值?對象範圍內的變量訪問

$("#selector").draggable({ 
    property1: "myvalue", 
    property2: "myvalue", 
    property3: "myvalue", 
    start: function() { 
     var runit = 'one value'; 
    }, 
    stop: function(){      
     //Access Value of runit 
     //Acess Value of property2 
    } 
}); 

回答

4

,因爲它是唯一的作用範圍是start()方法不能從stop()訪問runit。您應該能夠訪問property2

this.property2 

可以添加runit對象的屬性,如

{ 
    property1: "myvalue", 
    property2: "myvalue", 
    property3: "myvalue", 
    runit:  null, 
    start: function() { 
     this.runit = 'one value'; 
    }, 
    stop: function(){ 
     console.log(this.runit); 
     console.log(this.property2); 
    } 
} 

,可能爲工作的例子 - http://jsfiddle.net/9rZJH/

+1

如果你聲明沒有'var',你可以訪問runit。那麼這將是全球性的。 – bhamlin 2012-03-02 00:15:02

+0

@bhamlin乾杯,我已經澄清了我的回答 – Phil 2012-03-02 00:16:19

+0

雖然你應該**能夠在啓動和停止方法內訪問對象的範圍,但這不是一個安全的假設。這取決於他們如何在內部調用。 – David 2012-03-02 00:18:22

2

爲了訪問runit您需要在對象範圍外定義它:

var runit; 

$("#selector").draggable({ 
    property1: "myvalue", 
    property2: "myvalue", 
    property3: "myvalue", 
    start: function() { 
     runit = 'one value'; 
    }, 
    stop: function(){      
     //Access Value of runit 
     console.log(runit); 
     //Acess Value of property2 
     console.log(this.property2); 
    } 
}); 

property2應該通過this.property2是可訪問的,但取決於如何停止方法在內部調用。

+1

您的意思是「對象的範圍」,因爲沒有這樣的東西(在JS中)作爲對象範圍。 – davin 2012-03-02 00:19:08

+0

@davin當然:) – David 2012-03-02 00:21:13

1

另一種選擇是隻返回runit。我的意思是,這一切都取決於你想完成什麼:

start: function() { 
    var runit = 'one value'; 
    // Stuff 
    return { runit: runit }; 
}, 
method: function(){ 
    var foo = this.start().runit; 
}