最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Typescript gain current scope or variable inside function() - Stack Overflow

programmeradmin1浏览0评论

i use the JQuery load function to append (instead of replace) some html data to an element. My problem is the data is the this scope on the load function. Can not use () =>. How can i access a variable outside of the load callback ?

var element: JQuery;

$("<div></div>").load("", function {
   $(element).append(this);
});

i use the JQuery load function to append (instead of replace) some html data to an element. My problem is the data is the this scope on the load function. Can not use () =>. How can i access a variable outside of the load callback ?

var element: JQuery;

$("<div></div>").load("http://www.google.de", function {
   $(element).append(this);
});
Share Improve this question asked Jun 3, 2013 at 9:28 MR.ABCMR.ABC 4,86213 gold badges47 silver badges89 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

In TypeScript, when you use the () => syntax, it actually just creates a variable to contain the "current meaning of this" and then substitutes usages of this to call the generated variable. You can do this manually in situations where you want both meanings of this.

Here are some examples...

Normal use of this in a callback. this is the event target.

$('div').click( function () {
    // this is the clicked element
    alert('this: ' + this.id);
});

TypeScript arrow function used for a callback. this is the lexical scope.

$('div').click( () => {
    // this is the lexical scope
    // i.e. the containing class, containing function, or window
    alert('this: ' + this.id);
});

Manual example, creating a variable named self to contain the lexical scope and leaving this to be the event target.

var self = this;
$('div').click( function () {
    // this is the clicked element
    alert('this: ' + this.id);

    // self is the lexical scope
    // i.e. the containing class, containing function, or window
    alert('self: ' + self.id);
});

It is worth bearing in mind that JavaScript walks the scope chain at runtime, so if a variable isn't defined inside of a function, JavaScript inspects the enclosing function for the variable. It keeps walking up the chain until it has checked the global scope.

This example shows this in action, but the nesting can be much deeper and it still works (i.e. a function inside of innerFunction can still scope-walk to get to the test variable.

var example = function () {
    var test = 'A test';

    var innerFunction = function () {
        alert(test); // 'A test'
    }

    innerFunction();
}

example();

Just as you would expect. Any variable outside the function is available to you:

var element: JQuery;
var someOther = "123";

$("<div></div>").load("http://www.google.de", function(){
   $(element).append(this);
   $(this).text(someOther);
});
发布评论

评论列表(0)

  1. 暂无评论