![](/img/trans.png)
[英]How to define nodeCategoryProperty function for a Model in typescript?
[英]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 函數
您不能這樣做,因為getBear
的this
上下文在您調用它時未綁定到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.