English 中文(简体)
• 如何在javascript功能中起超级作用
原标题:How to make a super in javascript function

同这一例子一样:

var teste = {name: marcos };
$(teste).each(function(){

    var name = this.name; // i don t want to do that.

    // i want to have access to  this  inside this function (sayName)
    var sayName = function(){
        alert(name); // there is something like "super" in java? or similar way to do?
    }
    sayName();

});

如何做到这一点?

问题回答

this is never implicit in JavaScript (as it is in Java). This means that if you do not invoke a function as a method on an object, this will not be bound to something reasonable (it will be bound to the window object in the browser). If you want to have a this inside the function, that function should be used as a method, that is:

var teste = {name: marcos };
$(teste).each(function(){

    this.sayName = function(){
        alert(this.name); 
    }
    this.sayName();

});

Then sayName is a method and is invoked in this

我看到因特网上的许多例子(包括基于质量的事例):

var that = this;
var sayName = function() {
   alert(that.name);
}

这里还有另一种方式:

var teste = {name: marcos };
$(teste).each(function(){

var that = this;

var sayName = function(){
    alert(that.name);
}
sayName();

});

That is your super :-) Seriously, there is no "super" because it s not extension.





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

热门标签