为什么 this.prop 在构造函数中返回未定义

Why is this.prop in constructor returning undefined

我想了解以下代码日志中的明显差异 return。我希望它们是等价的,而不是 return undefined。但是,一个 return undefined 而另一个不

var floors = [ { number : 4, desc : `The obj from the floors array` } ]

function Unit ( number ) {
  this.number = number
  this.floor  = Number( String( this.number )[0] ) // no issue with a this.property reference here
  
  console.log( this.floor ) // evals to 4 here so why not on the next line?
  console.log( floors.find( function ( floor ) { return floor.number === this.floor } ) ) // Why does this return undefined
  console.log( floors.find( function ( floor ) { return floor.number === 4 } ) ) // but this does not?
}

new Unit ( 425 )

因为对于普通函数,this函数的调用方式 定义,而不是函数出现的位置。在您的 find 回调中,this 外部 您的 find 回调不同。

您至少有四个选项:

  1. 将第二个参数传递给 find:它定义了 this 回调中的内容:

    console.log( floors.find( function ( floor ) {
        return floor.number === this.floor;
    }, this ) );
    // ^^^^
    
  2. 使用Function#bind创建一个绑定函数:

    console.log( floors.find( function ( floor ) {
        return floor.number === this.floor;
    }.bind( this ) ) );
    // ^^^^^^^^^^^
    

    A bound 函数忽略调用它的 this,而是使用绑定到它的那个。

  3. 定义一个变量并将其设置为 this,然后在回调中使用该变量:

    var me = this; // The variable
    console.log( floors.find( function ( floor ) {
        return floor.number === me.floor;
    //                          ^^
    } ) );
    
  4. 从 ES2015 开始,您可以使用 箭头函数,它会关闭定义它的上下文的 this;在你的情况下,你可以使用没有 {}:

    concise 形式
    console.log( floors.find( floor => floor.number === this.floor ) );
    

    或者这是更长的形式:

    console.log( floors.find( floor => { return floor.number === this.floor; } ) );