我是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
值的函数,并且单独提供的论点。
this
是当前上下文,可用于扩展属性,但不能在其位置传递对象。
最简单的方法是在函数中添加对象作为参数,如
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;
}
}
在这个对象中,fullName需要随时访问名称和地址变量,无论您在哪个上下文中调用它
由于公司对象没有这些变量,这将尝试查找下一个范围以查找这些变量,这些变量可能存在,也可能不存在,这就是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)
注意即使接受的答案很好,它也无法达到使用打字脚本的目的。这个功能仍然很麻烦。