English 中文(简体)
Java底是什么?
原标题:How come JavaScript {this} doesn t reference the parent object?

提出反对 我假定this将退回标的书——相反,它似乎是其他东西。 为什么如此?

var Obj = { 
    foo :  value ,
    bar : function() { return this.foo; } // Error
    bar : function() { return Obj.foo; }  // Works
}

<>Update: 我必须找不到一些东西,因为在某些情况下,在物体内使用<>t><>t>/code>是没有工作的。 为什么只提到标语有时是?

最佳回答

确实如此。 你有一 issue子问题。

2. 界定反对成员

var Obj = { 
    foo :  value ,
    bar : function() { return this.foo; },
}

在成员职能范围内,this系指要求履行职务的物体。

rel=“nofollow”>jsFiddle Example

问题回答

在“ Java”字典功能栏目中,根据如何要求这一功能而确定。

您的榜样:Obj,假设你纠正了合成物的错误,并在特性之间使用mas:

var Obj = {
  foo :  value , // needs comma, not semicolon
  bar : function() { return this.foo; }
}

如果您使用<代码>Obj上的“dot” syntax, 称bar功能,this将自动定在上。 Obj :

Obj.bar(); // this will be Obj

这是确保<条码>的简便方法,最终确定了你想要的途径。 但是,如果你以某种其他方式把这一职能称作,那么<> 还可以确定:

var nonObjBar = Obj.bar; // get a reference to the function
nonObjBar(); // this will (probably) be `window`, but depends if
             // in strict mode or inside some other function, etc

var Obj2 = { foo: "other foo" };
Obj.bar.call(Obj2); // the .call() method sets this to Obj2
                    // so bar will return Obj2 s foo, "other foo"

最后一个例子使用<条码>:方法>,以允许你将<条码>这一条/代码>适用于你喜欢的任何事项(限制性方式与非限制性方式在某些情况下影响这项工作的方式)。

如果你从 Java等语言回来,这似乎很奇怪,但 Java文的功能不属于任何特定物体。 这种行为的定义和目的相当明确。

在对半殖民地进行估价之后,这似乎行之有效:

var Obj = { 
    foo :  value ,
    bar : function() { return this.foo; } // Error
};

alert(Obj.bar());   // alerts  value 

See working js Fiddle here:

当你把一种方法用在物体上时,javaster发动机将s点到该物体使用该方法期间。





相关问题
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.

热门标签