Just when I think I finally understand Javascript scope

不想你离开。 提交于 2019-12-18 13:30:39

问题


I run in to something that illustrates how I clearly don't get it yet.

Can anyone please explain why the value of "this" changes in the following?

var MyFunc = function(){
    alert(this);
    var innerFunc = function(){
        alert(this);
    }
    innerFunc();
};

new MyFunc();

回答1:


In JavaScript, this represents the context object on which the function was called, not the scope in which it was defined (or the scope in which it was called). For MyFunc, this references the new object being created; but for innerFunc, it references the global object, since no context is specified when innerFunc is called.

This tends to trip up those used to Java or similar OO languages, where this almost always references an instance of the class on which the method being called is defined. Just remember: JavaScript doesn't have methods. Or classes. Just objects and functions.

See also: What is the rationale for the behavior of the ‘this’ keyword in JavaScript?




回答2:


Just do the following:

var MyFunc = function(){
    var self = this;
    alert(self);
    var innerFunc = function(){
        alert(self);
    }
    innerFunc();
};

new MyFunc();

This way self will always mean this, irrespective of where you're calling it from, which is usually what you want.




回答3:


For a detailed explanation of closures, visit:

http://www.brockman.se/writing/method-references.html.utf8

Mr. Brockman illustrates clearly the problem you are having. I read this article every now and again simply for the sheer pleasure of being able to say, "Aha! I get it!"

For even more interesting JavaScript lessons, visit Douglas Crockford's "Wrrrld Wide Web" at

http://www.crockford.com/

As the creator of JSON, Mr. Crockford is "The Man" when it comes to JavaScript. He does not know me, but he has mentored my understanding of the beauty of JavaScript, nay, of programming in general.

You are this close to becoming a much better programmer than you are now. I say thins not in a demeaning sense, but from knowing how these two authors challenged my own skills.




回答4:


As a sidenote, "this" isn't necessarily referencing the actual function all the time, since you can invoke a function with a "forced" this-reference, think about an event-handler, in which this will refer to the actual element that fired the event.

using

yourFunction.apply(thisReference, arguments)

you can invoke it where "this" will point to whatever you pass on as first argument.




回答5:


At first glance I'd say it's because the outer 'this' is in reference to MyFunc and the inner 'this' is in reference to innerFunc.

However, Javascript isn't something I have any particular expertise in.



来源:https://stackoverflow.com/questions/652372/just-when-i-think-i-finally-understand-javascript-scope

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!