【问题标题】:method is not defined js方法未定义js
【发布时间】:2021-03-31 07:28:10
【问题描述】:

这段代码怎么会抛出一个

Uncaught ReferenceError:logRiver 未定义。

function createRiver (name, continent,lengthInKilometers){
    let obj = {
        name:  name,
        continent: continent,
        lengthInKilometers: lengthInKilometers,
        isLongerThan:function(riverObject) {
             if(this.lengthInKilometers>riverObject.lengthInKilometers)
                return true;
             else
                return false;
            
            },
         logRiver:function(){
            console.log(`The ${this.name} river is ${this.lengthInKilometers} kilometers 
            long.`)
        }
        }
        return obj;

}

和符号${}有关吗?​​

【问题讨论】:

  • 这段代码没有明显错误,请说明你在哪里使用了这个函数的结果
  • let test1=createRiver("Amazon","somecontinent",500) let test2=createRiver("Denoba","somecontinent",400) console.log(test1.isLongerThan(test2))//true console.log(logRiver(test2))//logRiver is not defined
  • @YakirAvraham 与.isLongerThan 相同,您需要致电test1.logRiver()
  • ……不,这与模板文字语法无关。

标签: javascript function syntax


【解决方案1】:

符号${} 是模板格式,用于在特殊模板(模板文字)字符串CODE 之间添加变量以替换这种形式的字符串写入,因此这里不是问题。

代码中的错误是您没有为 logRiver 部分定义任何函数或元素,然后尝试在不存在的术语 logRiver:function(){ 中运行函数

您所要做的就是将 logRiver 定义为某种东西,或者将函数重新格式化为正确的箭头格式,然后调用它下面的函数。例如

// with logRiver being returned as a constant you can reference later and this being an inputted object with the needed information
const logRiver = function (example){
  console.log(`The ${example.name} river is ${example.lengthInKilometers} kilometers long.`);
};

// then you can call it to check

console.log(logRiver);

编辑:我的错误 - 似乎logRiver: 是另一种格式,用于执行我定义的我不知道的相同事情。那么问题就出在代码的测试数据中。

【讨论】:

  • 不能使用this作为参数名。
  • 是的,我的错 - 我只是将它用作输入器信息数组的示例参数名称。 OP 应该遵循良好的命名标准
猜你喜欢
  • 1970-01-01
  • 2019-03-27
  • 1970-01-01
  • 1970-01-01
  • 2015-11-29
  • 2021-07-01
  • 1970-01-01
  • 2013-11-10
  • 1970-01-01
相关资源
最近更新 更多