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));
添加回答
舉報