Javascript访问函数内的父对象

时间:2011-06-20 03:40:07

标签: javascript json

我有这个Car功能:

var Car = function(vendor, model, year) {
    return {
        vendor: vendor,
        model: model,
        year: year,
        name: (function() {
            return vendor + " " + model + " " + year;
        })()
    };
};
var foo = Car("Toyota","Corola",2007);
alert(foo.name);  //alerts "Toyota Corola 2007"

这样做有效,但我希望name能够根据vendormodelyear进行更改。

taxi.vendor = "Mitsubishi";
alert(taxi.vendor); //still alerts "Toyota Corola 2007"

如何根据Mitsubishi Corola 2007属性的变化将其设为vendor

编辑:捕获 - name必须保留为不需要作为函数调用的属性。

3 个答案:

答案 0 :(得分:3)

使用最新版本的WebKit(Safari,Chrome)或Firefox,您可以define getter and setter functions

var o = {a: 7, get b() {return this.a + 1;}, set c(x) {this.a = x / 2}};
o.b // result is 8
o.a = 10
o.b // result is 11

然后你会这样做:

var Car = function(vendor, model, year) {
    return {
        vendor: vendor,
        model: model,
        year: year,
        get name() { return this.vendor + " " + this.model + " " + this.year; }
    };
};

获得你想要的结果。

我不知道IE或Opera是否支持这个或哪个版本。如果您需要支持除最近的Safari,Chrome或Firefox浏览器以外的任何内容,那么您最好使用函数来访问该名称,而不是将其作为属性保留:

var Car = function(vendor, model, year) {
    return {
        vendor: vendor,
        model: model,
        year: year,
        name: function() { return this.vendor + " " + this.model + " " + this.year; }
    };
};

然后:

var foo = Car("Toyota","Corola",2007);
alert(foo.name());  //alerts "Toyota Corola 2007"
foo.vendor = "Mitsubishi";
alert(foo.name());  //alerts "Mitsubishi Corola 2007"

答案 1 :(得分:2)

怎么样:

 var Car = function(thevendor, themodel, theyear) {
    this.vendor = thevendor;
    this.model = themodel,
    this.year = theyear,
    this.name = function() {
            return this.vendor + " " + this.model + " " + this.year;
        };
    return this;
};


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代码:http://jsfiddle.net/duncan_m/gZKQD/

答案 2 :(得分:2)

使用name: (function() {return vendor + " " + model + " " + year;})()时,这意味着name属性将设置为执行此功能的结果。创建新Car时会发生这种情况。但听起来你想要动态更新,所以考虑让name成为一个getter函数而不仅仅是一个字符串属性:

name: function() {return vendor + " " + model + " " + year;}

然后你可以alert(taxi.name()),它将动态连接供应商,模型和年份字符串。