【发布时间】:2023-04-11 06:56:01
【问题描述】:
我正在学习 JS,但我有点无法理解发生了什么。
我在按下按钮时拨打function,但o/p 说它是undefined。为什么我收到undefined?我认为我没有将对象作为一个整体传递,因此它无法从中引用,但是当我尝试在添加事件侦听器的callBack 函数之外打印它时,我得到了正确的 O/P。
const buttonM = document.getElementById("demo");
let object = {
name: "Utkarsh",
surname: "sharma",
roll: 23,
objectFunction: function () {
console.log("Value is :" + this.name + " Surname:" + this.surname);
},
};
object.objectFunction(); //op: Value is: Utkarsh Surname: Sharma (correct op as expected).
buttonM.addEventListener("click", object.objectFunction); //on pressing the button op:value is: Surname:Undefined (expected o/p is: Value is: Utkarsh Surname: Sharma).
cmets 带有 op(输出)
【问题讨论】:
标签: javascript html css angularjs reactjs