【问题标题】:How to define a function with "this" context in typescript如何在打字稿中使用“this”上下文定义函数
【发布时间】:2021-12-18 11:06:30
【问题描述】:
type Animal = {
    name: string
}

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

console.log(getBear().name)

谁能帮我解决这个问题,我无法调用 getBear 函数

【问题讨论】:

  • 您明确定义this 必须是Animal,但是您在没有对象上调用getBear 所以它是void

标签: javascript typescript typescript-typings


【解决方案1】:

您可以通过 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)

【讨论】:

    【解决方案2】:

    您不能这样做,因为当您调用它时,getBearthis 上下文未绑定到 Animal。仅仅告诉 TypeScript thisAnimal 是不够的,你还必须使用该上下文调用你的函数。

    在这种情况下,您需要这样称呼它。

    type Animal = {
        name: string
    }
    
    function getBear(this: Animal) : Animal {
        this.name = "hi"
        return this
    }
    
    console.log(getBear.call({ name: "test" }).name)
    

    【讨论】:

      猜你喜欢
      • 2019-02-03
      • 2021-04-25
      • 2018-12-27
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多