我剛開始學習javascript,似乎無法正確呼叫物件方法。我什至從這里復制粘貼了代碼以嘗試理解我的錯誤,但它只是將代碼作為字串回傳。我的代碼:
function greetings(name){
document.getElementById('someText').innerHTML = 'Hello' ' ' name;
}
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName " " this.lastName;
}
};
greetings(person.fullName);
<div id="someText"></div>
結果:
你好 function() { return this.firstName " " this.lastName; }
uj5u.com熱心網友回復:
您必須呼叫該方法,該方法將回傳一個人名字串,然后將其傳遞給 greetings 函式。
如果沒有()該方法,則不會執行該方法,并且該方法本身將傳遞給 greetings 函式。
由于它在函式中被視為字串,因此您會在函式上呼叫 toString() 方法,從而生成函式代碼本身。
function greetings(name){
document.getElementById('someText').innerHTML = 'Hello' ' ' name;
}
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName " " this.lastName;
}
};
greetings(person.fullName());
console.log(person.fullName.toString());
<div id="someText"></div>
uj5u.com熱心網友回復:
因為您fullname在這里定義為函式:
fullName: function() {
return this.firstName " " this.lastName;
}
那么你必須呼叫它,比如:greetings(person.fullName());末尾有額外的括號
uj5u.com熱心網友回復:
您可以通過兩種方式解決您的問題。
//firstly
greetings(person.fullName()); // calling the function when you pass it as a Arguments.
// secondly
function greetings(name){
document.getElementById('someText').innerHTML = 'Hello' ' ' name();
// if you always except a function as a peramiter just call it when you use it.
}
您將 fullName 定義為一個人物件屬性,它是一個函式。為了獲得正確的值,您必須呼叫該函式。我們在函式名之后使用 () 來呼叫它。如果函式沒有呼叫它回傳函式體。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/482098.html
標籤:javascript
上一篇:當有人在Javascript中輸入全名時如何獲取名字和姓氏?
下一篇:我正在嘗試向我的反應組件發出axiosGET請求,我在console.log上獲取物件。但是當我嘗試渲染它時,我得到一個“未定義”
