我有一个程序:
$(document).ready(function() {
this.name = "John";
var someFunc = function()
{
return this.name;
}
});
根据我的理解,' 这个'在someFunc
中是"窗口"因为它不包含在任何对象中。
我的问题是为什么' this
'是' HtmlDocument
'在$(document).ready(function() { alert(this) }
?
由于someFunc
位于$(document).ready
函数之下,为什么它的价值不能是' HtmlDocument
'还有?
究竟发生在幕后的是什么导致了这种情况在不同情况下的价值不同?
答案 0 :(得分:1)
阅读this(https://remysharp.com/2007/04/12/jquerys-this-demystified),例如在java脚本中简要概述“this”:
答案 1 :(得分:1)
变量public function destroy(Request $request)
{
$ids = $request->input('deletecolor');
// Instead of raw SQL, you can use the query builder to make your life a bit easier
$affected = DB::table('vehicle_color')->whereIn('id', $ids)->delete();
//echo $affected==1?"Successfully Deleted":"Delete Fail";
}
在JavaScript中有一个范围概念,其值取决于您访问它的位置,我尝试用示例解释一下,请参阅以下代码段:
this

$("#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 );

正如您所看到的,<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" />
始终引用其所有者&#34;对象,所以当你在任何类型的对象之外声明一个函数时,它的所有者是this
对象,否则它引用定义函数的对象。
总结:
window
我希望我很清楚,再见。