如何在 JS/jQuery 对象文字中定义的事件回调中引用对象本身?
我研究了各种答案和文章,比如这个问题:How to access the correct `this` inside a callback?但却发现自己更加困惑。
this
应该引用被单击的元素,因为我们需要访问它,这是有道理的,但是我如何引用包含绑定(bind)函数本身的对象呢?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>This</title>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
</head>
<body>
<button id="test">Click Me</button>
<script>
$( document ).ready( function() {
console.log(MyObj.introspect());
MyObj.bindEvents();
} );
MyObj = {
myProperty : 'a property',
bindEvents : function(){
$('#test').on('click', MyObj.introspect)
},
introspect : function(){
console.log(this);
}
}
</script>
</body>
</html>
最佳答案
就您而言,您将使用 MyObj
,就像您在 bindEvents
中所做的那样,因为它是单例:
MyObj = {
myProperty : 'a property',
bindEvents : function(){
$('#test').on('click', MyObj.introspect)
},
introspect : function(){
console.log(MyObj);
// ---------^^^^^
}
}
<小时/>
旁注:您的代码正在成为我所说的 The Horror of Implicit Globals 的牺牲品。请务必声明您的变量(使用 var
或 ES2015 的 let
或 const
)。在您的情况下,您可以将 MyObj
设为完全私有(private),因为您只需在自己的代码中需要它,只需将其移至 ready
回调中并声明它即可:
$( document ).ready( function() {
var MyObj = { // Note the `var`
myProperty : 'a property',
bindEvents : function(){
$('#test').on('click', MyObj.introspect)
},
introspect : function(){
console.log(MyObj);
}
}; // Also added missing ; here
console.log(MyObj.introspect());
MyObj.bindEvents();
});
关于javascript - JS 对象文字中的 "This"- 事件回调中的不同含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51669964/