【问题标题】:Javascript Accessing Parent Object inside FunctionJavascript访问函数内的父对象
【发布时间】:2011-06-21 01:38:38
【问题描述】:

我有这个 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"

如何根据vendor属性的变化,让它提醒Mitsubishi Corola 2007

编辑:还有问题 -- name 必须保留一个不需要作为函数调用的属性。

【问题讨论】:

标签: javascript json


【解决方案1】:

使用最新版本的 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"

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 是否可以不将name 设为函数?
    • 如果您想在不将 name 设为函数的情况下执行此操作,则必须创建 setter 函数(例如 setVendorsetModelsetYear),以便每次都发生变化你可以重新创建name。您也可以使用getters and setters 作为另一位提到的评论者。
    【解决方案3】:

    怎么样:

     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/

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-29
      • 2015-06-26
      • 1970-01-01
      • 2011-10-07
      • 1970-01-01
      相关资源
      最近更新 更多