3 回答
TA贡献1783条经验 获得超4个赞
原因是因为this引用不同。
当您最初调用该object.objectFunction();函数时,您this就是对象本身,并且它具有name和的键surname。
当您将object.objectFunction函数附加到按钮的点击侦听器时,将创建对该函数的引用,并且您将丢失其余object属性。
希望一个例子可以解决这个问题:
const buttonM = document.getElementById("demo");
let object = {
name: "Utkarsh",
surname: "Sharma",
objectFunction: function () {
console.log("this →", this); // ← I have added this line
console.log("name →", this.name)
console.log("surname →", this.surname)
},
};
object.objectFunction();
buttonM.addEventListener("click", object.objectFunction);
<button id="demo">click</button>
TA贡献1851条经验 获得超4个赞
当您调用objectFunction时object,它会起作用,正如您已经发现的那样。但是,当实际function被定义为事件处理程序时,它不再绑定到对象。您可以创建一个调用它的函数,例如
const buttonM = document.getElementById("demo");
let object = {
name: "Utkarsh",
surname: "sharma",
roll: 23,
objectFunction: function () {
console.log(this);
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).
请参阅:https ://jsfiddle.net/561so8e2/
或者您可以将对象绑定到点击,如
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.onclick = object.objectFunction;
buttonM.onclick.bind(object);
//buttonM.addEventListener("click", () => {object.objectFunction()}); //on pressing the button op:value is: Surname:Undefined (expected o/p is: Value is: Utkarsh Surname: Sharma).
请参阅https://jsfiddle.net/561so8e2/2/
TA贡献2041条经验 获得超4个赞
只需将对象绑定到它应该工作的回调
const buttonM = document.getElementById("demo");
let object = {
name: "Utkarsh",
surname: "sharma",
roll: 23,
objectFunction: function () {
let self = this;
console.log("Value is :" + self.name + " Surname:" + self.surname);
},
};
object.objectFunction(); //op: Value is: Utkarsh Surname: Sharma (correct op as expected).
buttonM.addEventListener("click",object.objectFunction.bind(object));
添加回答
举报