English 中文(简体)
访问 Javascript 对象中的内变量
原标题:accessing an inner variable in a javascript object
  • 时间:2012-05-24 15:30:11
  •  标签:
  • javascript

考虑此错误代码 :

x = {
  y : "why",
  z : function() {
    return y + " zed";
  }
}

函数z 不工作 : “ 引用错误: y 未定义 。 ”

是否有办法从函数 z 中访问 y,而不完全指定为 x.y?

我当然可以改写为

x = function() {
  var self = this;
  this.y = "why";
  this.z = function() {
    return self.y + " zed";
  };
  return this;
}();

...但耶稣。

问题回答

如果您以 x.z () 调用此函数, 请简单使用 this :

var x = {
    y : "why",
    z : function() {
        return this.y + " zed";
    }
};

DEMO: http://jsfiddle.net/hZxVu/

否, 您需要重写它本身。 y 是该对象的属性, 您无法在没有对象的情况下访问它 - 不同于从关闭时访问变量( 如: self ) 。

当然,当您援引该函数为 x.z () 时, 此 关键词 也将指向对象,以便您能够按此写成

return this.y + " zed";

只要您一直 调用该对象上下文中的函数。

@VisioN 有直向前的答案。 如果您重写您的代码, 这可能有助于想象为什么有必要这样做:

var x = {};
x.y = "why";
x.z = function() {return this.y + " zed"; };
alert(x.z());

这里的 y 和 z 是对象的属性, 但是没有功能关闭范围。 您需要“ 此” 关键字才能访问父对象的属性 。

或者,

var x = function () {
    var y = "why";     
    var z = function () { return y + " zed?"; };    
    return z();
};
alert(x());

这将通过访问 y 而不用此功能来显示功能范围界定。 在 < code> x 中, < code> < y 是已知的。 在外部, 它不是 。

使用显示模块模式 :

    var x = (function () {
        y = "why";
        z = function() {
            return y + " zed";
        };
        return {
            "y": y,
            "z": z
        };
    })();

    //now you can call:
    x.y // "why"
    x.z() // "why zed"




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.