3 回答

TA貢獻(xiàn)1783條經(jīng)驗(yàn) 獲得超4個(gè)贊
原因是因?yàn)閠his引用不同。
當(dāng)您最初調(diào)用該object.objectFunction();函數(shù)時(shí),您this就是對(duì)象本身,并且它具有name和的鍵surname。
當(dāng)您將object.objectFunction函數(shù)附加到按鈕的點(diǎn)擊偵聽器時(shí),將創(chuàng)建對(duì)該函數(shù)的引用,并且您將丟失其余object屬性。
希望一個(gè)例子可以解決這個(gè)問題:
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貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超4個(gè)贊
當(dāng)您調(diào)用objectFunction時(shí)object,它會(huì)起作用,正如您已經(jīng)發(fā)現(xiàn)的那樣。但是,當(dāng)實(shí)際function被定義為事件處理程序時(shí),它不再綁定到對(duì)象。您可以創(chuàng)建一個(gè)調(diào)用它的函數(shù),例如
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).
請(qǐng)參閱:https ://jsfiddle.net/561so8e2/
或者您可以將對(duì)象綁定到點(diǎn)擊,如
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).
請(qǐng)參閱https://jsfiddle.net/561so8e2/2/

TA貢獻(xiàn)2041條經(jīng)驗(yàn) 獲得超4個(gè)贊
只需將對(duì)象綁定到它應(yīng)該工作的回調(diào)
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));
添加回答
舉報(bào)