簡體   English   中英

如何在打字稿中定義帶有“this”上下文的函數

[英]How to define a function with "this" context in typescript

type Animal = {
    name: string
}

function getBear(this: Animal) : Animal {
    this.name = "hi"
    return this
}

console.log(getBear().name)

任何人都可以幫我解決這個問題,我無法調用 getBear 函數

您不能這樣做,因為getBearthis上下文在您調用它時未綁定到Animal 簡單地告訴 TypeScript this是一個Animal是不夠的,您還必須使用該上下文調用您的函數。

在這種情況下,您需要像這樣調用它。

type Animal = {
    name: string
}

function getBear(this: Animal) : Animal {
    this.name = "hi"
    return this
}

console.log(getBear.call({ name: "test" }).name)

您可以通過 3 種方式調用它:

type Animal = {
    name: string
}

function getBear(this: Animal, a: string): Animal {
    this.name = a
    return this
}

// First one 

// function.call(objcontext,parameters) calls a function under a different object context.
// read more at : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

console.log(getBear.call({ name: "test" }, "Username").name)

// Here we create a object 
//second
console.log(new (getBear as any)("Username").name)

//third
console.log(new (<any>getBear)("Praveen").name)

暫無
暫無

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

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