I see this code, what's it doing?
var ob开发者_如何学JAVAj = this;
It's just storing the current reference of this
object, to be used in future. It's useful, because in JS value of this
depends on a context.
It saves a reference to whatever this
was in the current context, so it can be used later.
That is setting a local copy of the current first class function that its being set in.
This is used ALOT in jquery as this takes on a different meaning when you being using the selectors.
Say I have a
function Person() {
this.name = "gnostus";
}
and I need to access name from inside a jquery selector, where this becomes an html element, I would store my object into a copy variable and use, obj.name
in place of this.name
when im inside of the jquery context.
It depends where this statement is located. It assigns to variable "obj" reference to current object.
for example the following code will open an alert window and show [Window object]. That's because we check value of "this" in the body area (not inside any objects event handler, etc.)
<html>
<head>
</head>
<body>
<script type="text/javascript">
alert(this);
</script>
</body>
</html>
It's creating a variable 'obj' and setting it to the current context.
So, for example, if it's at a global level this
would be the current DOM Window.
var obj = this;
Is stating, assign obj with the parent of the current scope.
I first read this post a couple months ago to get a handle on the keyword 'this'.
http://justin.harmonize.fm/index.php/2009/09/an-introduction-to-javascripts-this/
The this keyword is used to refer to the owner of the function , or the variable the this keyword is used in. For a detailed understanding visit http://www.quirksmode.org/js/this.html
The only context I can think of where this sort of code makes sense is to make the current context (this) available inside a closure.
So the code would be something like:
var obj = this;
setTimeout(function() {
obj.someMethod();
}, 1000);
That would call the method "someMethod" on the current context object after 1 second goes by.
精彩评论