簡體   English   中英

typescript中調用方法出錯

[英]Errors in call method in typescript

我是 typescript 的初學者,我試圖實現這段代碼,但在第 3 行出現 2 個錯誤。它顯示名稱和地址未定義。 誰能幫我使這段代碼可行。

var company = {
    fullName: function(ceo :string, teamcount :string) :string {
        return "Name :- " + this.name + "\nAddress:- " + this.address + "\nCEO :- " + ceo + "\nTeamCount :- " + teamcount;
        }
    }

var company1 = {
    name:"BOB the builder",
    address: "Disney world"
}


const temporaryVariable = company.fullName.call(company1,"BOB","30")
console.log(temporaryVariable)

根據定義

call() 方法使用給定的this值調用 function 並單獨提供 arguments。

this是當前上下文,可用於擴展屬性,但您不能在其位置傳遞 object。

最簡單的方法是將 object 作為參數添加到您的 function 中,例如

var company = {
    fullName: function(data: any,ceo :string, teamcount :string) :string {
        return "Name :- " + data.name + "\nAddress:- " + data.address + "\nCEO :- " + ceo + "\nTeamCount :- " + teamcount;
        }
    }

然后將您的call更新為以下

const temporaryVariable = company.fullName.call(this, company1, "BOB","30");
var company = {
fullName: function(ceo :string, teamcount :string) :string {
    return "Name :- " + this.name + "\nAddress:- " + this.address + "\nCEO :- " + ceo + "\nTeamCount :- " + teamcount;
    }
}

在這個 object 中,fullName 需要隨時訪問名稱和地址變量,無論您在哪個上下文中調用它。

由於公司object 沒有這些變量,這將嘗試立即查看下一個 scope 以找到那些可能存在或可能不存在的變量,這就是 TS 抱怨的原因[記住你可能不想在期間破壞代碼運行時,因為可能找不到名稱和地址]。

例如:在以下兩種情況下,即使 TS 顯示錯誤,它對您的代碼也能正常工作,請檢查日志

但是,在這種情況下運行它時它不起作用

因此,將 TS 用於它應該使用的目的(在運行時防止錯誤)

你可能想像這樣重構它

 var company = {
    fullName: function({name, address, ceo, teamcount}: {
        name: string;
        address: string;
        ceo: string;
        teamcount: string;
    }): string {
        return "Name :- " + name + "\nAddress:- " + address + "\nCEO :- " + ceo + "\nTeamCount :- " + teamcount;
        }
    }

var company1 = {
    name:"BOB the bulider",
    address: "Disney world"
}

// Works
const temporaryVariable1 = company.fullName({...company1, ceo:"BOB", teamcount: "30"})
console.log(temporaryVariable1)

// Example to show how it prevent bug
var company2 = {
    test:"BOB the bulider",
    address: "Disney world"
}

// TS complains, so you know you can't pass this objectto fullName function
const temporaryVariable2 = company.fullName({...company2, ceo:"BOB", teamcount: "30"})

console.log(temporaryVariable2)

注意即使接受的答案工作正常,它也違背了使用 typescript 的目的。function 仍然存在問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM