Javascript Accessing Parent Object Inside Function
Solution 1:
With recent versions of WebKit (Safari, Chrome) or Firefox, you can define getter and setter functions:
var o = {a: 7, getb() {returnthis.a + 1;}, setc(x) {this.a = x / 2}};
o.b // result is 8
o.a = 10
o.b // result is 11
Then you would do this:
var Car = function(vendor, model, year) {
return {
vendor: vendor,
model: model,
year: year,
get name() { returnthis.vendor + " " + this.model + " " + this.year; }
};
};
And get the result that you want.
I don't know if IE or Opera support this or which versions. If you need to support anything other than recent Safari, Chrome, or Firefox browsers then you're better off using a function to access the name instead of leaving it as a property:
var Car = function(vendor, model, year) {
return {
vendor: vendor,
model: model,
year: year,
name: function() { returnthis.vendor + " " + this.model + " " + this.year; }
};
};
And then:
var foo = Car("Toyota","Corola",2007);
alert(foo.name()); //alerts "Toyota Corola 2007"
foo.vendor = "Mitsubishi";
alert(foo.name()); //alerts "Mitsubishi Corola 2007"
Solution 2:
When you use name: (function() {return vendor + " " + model + " " + year;})()
, that means that the name
property will be set to the result of executing this function. This happens when you create a new Car
. But it sounds like you want this to update dynamically, so consider having name
be a getter function instead of just a string property:
name: function() {return vendor + " " + model + " " + year;}
Then you can do alert(taxi.name())
, which will dynamically concatenate the vendor, model, and year strings.
Solution 3:
How about:
var Car = function(thevendor, themodel, theyear) {
this.vendor = thevendor;
this.model = themodel,
this.year = theyear,
this.name = function() {
returnthis.vendor + " " + this.model + " " + this.year;
};
returnthis;
};
var foo = new Car("Toyota","Corola",2007);
alert(foo.name()); //alerts "Toyota Corola 2007"
foo.vendor = "Mitubishi";
alert(foo.name()); //alerts "Mistubishi Corola 2007"
JSFiddle for this code: http://jsfiddle.net/duncan_m/gZKQD/
Post a Comment for "Javascript Accessing Parent Object Inside Function"