Angular 将变量值重新指定为参数
我想重新分配一个通过多个函数的变量Angular 将变量值重新指定为参数,angular,Angular,我想重新分配一个通过多个函数的变量 public name: string; public secondName: string; public thirdName: string; functionA(name: string) { this.functionB(name); } functionB(name: string) { name = "Hello World"; } 在function()中调用变量时,我希望将变量重新分配到“Hello World”,如下所示 f
public name: string;
public secondName: string;
public thirdName: string;
functionA(name: string) {
this.functionB(name);
}
functionB(name: string) {
name = "Hello World";
}
在function()中调用变量时,我希望将变量重新分配到“Hello World”,如下所示
functionA(this.name);
console.log(this.name);
这里怎么了?Console.log输出未定义。我知道functionB()中的“name”并不直接引用this.name,这就是问题所在,我想找到一种方法让“name”引用this.name。字符串是按值传递的,而不是按引用传递的。当您将
this.name
传递给functionB并由functionB更改时,functionB只更改参数的值
要确保它更改此.name,可以执行以下操作:
公共名称:字符串;
函数(){
这个.functionB(“hello world”);
}
函数B(名称设置:字符串){
this.name=nameToSet;
log(nameToSet,this.name);
}
文章:字符串是通过值传递的,而不是通过引用传递的。当您将
this.name
传递给functionB并由functionB更改时,functionB只更改参数的值
要确保它更改此.name,可以执行以下操作:
公共名称:字符串;
函数(){
这个.functionB(“hello world”);
}
函数B(名称设置:字符串){
this.name=nameToSet;
log(nameToSet,this.name);
}
文章:你应该使用
这个.名称
,而不仅仅是名称
。
您的代码如下所示:
public name: string;
functionA() {
this.functionB(this.name);
}
functionB(name: string) {
this.name = "Hello World";
console.log('name', this.name);
}
寻找现场演示您应该使用
this.name
而不仅仅是name
。
您的代码如下所示:
public name: string;
functionA() {
this.functionB(this.name);
}
functionB(name: string) {
this.name = "Hello World";
console.log('name', this.name);
}
查找现场演示您正在尝试获取此名称的值。在类或组件中,您只声明了属性“public name:string;”,但没有设置它。因此,该属性似乎是“未定义的”=>这在您的示例中是正确的 本地函数变量
name
当然被设置为字符串“Hello World”,它可以工作
如果要设置this.name
,需要在函数B中设置它,如:
functionB(name: string) {
this.name = name;
console.log(name, this.name);
}
您正在尝试获取this.name的值。在类或组件中,您只声明了属性“public name:string;”,但没有设置它。因此,该属性似乎是“未定义的”=>这在您的示例中是正确的
本地函数变量name
当然被设置为字符串“Hello World”,它可以工作
如果要设置this.name
,需要在函数B中设置它,如:
functionB(name: string) {
this.name = name;
console.log(name, this.name);
}
这是我已经拥有的,但不幸的是我不能这样做,因为我有很多变量,这意味着为每个变量创建一个函数。我的目标是只使用2个通用函数将它们中的任何一个指定给“Hello World”!哦,好的。你能提供关于完整用例的更多细节吗?(为了更好地理解它)您的链接实际上解决了我的问题,我想:我只能修改主变量,如果它是数组或对象。当我传递文本时,我可以给我的函数赋值。这是我已经有的,但不幸的是我不能这样做,因为我有很多变量,这意味着为每个变量创建一个函数。我的目标是只使用2个通用函数将它们中的任何一个指定给“Hello World”!哦,好的。你能提供关于完整用例的更多细节吗?(为了更好地理解它)您的链接实际上解决了我的问题,我想:我只能修改主变量,如果它是数组或对象。当我传递文本时,我可以给我的函数赋值。