函数参数返回undefined
问题描述:
我遇到了函数语法的问题,当我调用函数并给出它的两个参数字符串时,输出始终未定义。我不明白为什么要这样做,我也想知道这是否可以继续进行堆栈交换的代码审查部分,因为它没有bug。任何答案将不胜感激!函数参数返回undefined
function sm(name, location){
console.log("Hello " + this.name + " from " + this.location);
}
sm("josh", "hawaii");
答
无需使用this
的功能参数。
function sm(name, location){
console.log("Hello " + name + " from " + location);
}
sm("josh", "hawaii");
答
的function
参数不是函数的性质,所以你不能用this
关键字访问它们。
而在你的功能this
将涉及全球window
对象,编译器会寻找window
对象内这些属性,如果没有定义,他们将触发一个例外。
只要写:
console.log("Hello " + name + " from " + location);
演示:
function sm(name, location){
console.log("Hello " + name + " from " + location);
}
sm("josh", "hawaii");
答
function sm(name, location){
console.log("Hello " + name + " from " + location);
}
sm("josh", "hawaii");
希望它可以帮助你
答
你不需要在这里使用this
这里。只需要name
和location
就足以将传递的变量作为函数参数。
function sm(name, location){
console.log("Hello " + name + " from " + location);
}
sm("josh", "hawaii");
'this.name'没有了'name'您在参数中传递的'this'是指'Window'的'name'和'location'财产。只需使用'name'和'location'而不用'this'。 –