【问题标题】:Javascript doesn't return properly?Javascript 不能正确返回?
【发布时间】:2018-03-22 04:56:36
【问题描述】:

我在学习 Javascript 的过程中遇到了apply 函数。我想我可以将我的apply 值分配给一个变量,然后打印出变量的内容。但是,我似乎没有定义,我不确定为什么会这样......

var thisObj = {
    fullName: 'test',
  setName: function(firstName, lastName) {
    this.fullName = firstName + " " + lastName
  }
}

function getInput(firstName, lastName, callBack, createdObj) {
    return callBack.apply(createdObj, [firstName, lastName]);
}

var thisObjectInstantiated = getInput("Michael", "Jackson", thisObj.setName, thisObj);
console.log(thisObjectInstantiated); // Why is this undefined?

我还注意到,如果我将打印更改为这样的事情,我的名字是正确定义的。

var thisObjectInstantiated = getInput("Michael", "Jackson", thisObj.setName, thisObj);
console.log(thisObj.fullName); // This is defined properly!

为什么我不能只将应用的结果存储在thisObjectInstantiated 变量中?谢谢。

【问题讨论】:

  • 函数setName不返回任何东西,所以它是undefined

标签: javascript apply


【解决方案1】:

您正在调用 getInput 函数,即调用 setName 函数,它不返回任何内容,所以 thisObjectInstantiated 正在接收...什么都没有!

您可能希望像这样更改您的代码:

var thisObj = {
fullName: 'test',
setName: function(firstName, lastName) {
     this.fullName = firstName + " " + lastName;
     return this;
   }
 }

【讨论】:

  • 返回thisthis.fullName?
  • 因为变量被称为thisObjectInstantiated,所以返回一个thisObj实例是有意义的
【解决方案2】:

您正在分配函数调用的结果,在您的代码中,没有返回值。这就是你得到undefined的原因。

执行的代码没有返回值,所以JavaScript默认返回值为undefined

【讨论】:

    猜你喜欢
    • 2016-09-03
    • 2019-11-22
    • 1970-01-01
    • 1970-01-01
    • 2013-04-23
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    相关资源
    最近更新 更多