How to define a variable which can be accessed by all my functions in my object?
I have a object like this:
myobj={
//where to define Car car=new Car();
test:{
testFunc1(){car.paintTest();},
testFunc2(){car.drawTest();}
},
use:{
useFunc1(){car.paintUse();},
useFunc2(){car.drawUse();}
},
};
I will use myobj
in the way that, in another js file, I can easily call
myobj.test.testFunc2();
or
myobj.use.useFunc1();
As you notice, in myobj
, I have a car
instance frequently be used in different functions in different sub-objects (e.g. "test", "use" sub-objects).
I am wondering, where can I define Car car=new Car();
in myobj
so that the car
开发者_如何学Gois defined once and can be used in several functions in myobj
.
you can do that like this:
myobj={
car: new Car(),
test: {
var self = this;
testFunc1(){self.car.paintTest();},
testFunc2(){self.car.drawTest();}
},
use: {
var self = this;
useFunc1(){self.car.paintUse();},
useFunc2(){self.car.drawUse();}
},
};
UPDATE
working version with fake Car
object:
function Car (){
this.paintTest = function(){console.log('painttest')}
this.drawTest = function(){console.log('drawtest')}
this.paintUse = function(){console.log('paintuse')}
this.drawUse = function(){console.log('drawuse')}
}
myobj = {
car: new Car(),
test:{
testFunc1: function() {myobj.car.paintTest();},
testFunc2: function() {myobj.car.drawTest();}
},
use: {
useFunc1: function(){myobj.car.paintUse();},
useFunc2: function(){myobj.car.drawUse();}
},
};
myobj.test.testFunc1();
myobj.test.testFunc2();
myobj.use.useFunc1();
myobj.use.useFunc2();
fiddle: http://jsfiddle.net/maniator/KcQvL/
精彩评论