函数中’this’的值
我有一个程序:
$(document).ready(function() { this.name = "John"; var someFunc = function() { return this.name; } });
根据我的理解, someFunc
中’ this ‘的值是“window”,因为它不包含在任何对象中。
我的问题是为什么$(document).ready(function() { alert(this) }
中’ this
‘的值是’ HtmlDocument
‘?
而且因为someFunc
在$(document).ready
函数下,为什么它的值不能也不是’ HtmlDocument
‘? 究竟发生在幕后的是什么导致了它在不同情况下的价值不同?
阅读本文 ( https://remysharp.com/2007/04/12/jquerys-this-demystified ),例如在java脚本中简要概述“this”:
这个变量在JavaScript中有一个范围概念,它的值取决于你访问它的位置,我试着用一个例子解释一下,参见下面的代码片段:
$("#document").ready(function() { console.log("HERE 'this' references to its owner object \"HTMLDocument\""); console.log(this.toString()); jsFunction(); $("#test").jqueryFunction(); console.log("You could call jsFunction on window:"); window.jsFunction(); console.log("But you can't call jqueryFunction on window:"); try{ window.jqueryFunction(); }catch(err){console.log("error");} console.log("Neither you could call jsFunction on \"div test\":"); try{ $("#test").jsFunction(); }catch(err){console.log("error");} //Inner functions console.log("The same thing applies to inner functions"); var innerFunc = function(){ console.log(this.toString()); var moreInnerFunc = function(){ console.log(this.toString()); } moreInnerFunc(); } innerFunc(); (function(){ console.log("Immediately-Invoked Function Expression (IIFE)"); console.log(this.toString()); })(); var extDeclared = externallyDeclared; extDeclared(); $("#document").extDeclared(); }); function jsFunction(){ console.log("HERE 'this' references to its owner \"window\""); console.log(this.toString()); } (function( $ ){ $.fn.jqueryFunction = function() { console.log("HERE 'this' references to its owner \"div test\""); console.log($(this).prop("id")); }; })( jQuery ); function externallyDeclared(){ console.log("externallyDeclared may be window or its other owner"); console.log(this.toString()); } (function( $ ){ $.fn.extDeclared = externallyDeclared; })( jQuery );