为什么构造函数中的this.prop返回undefined

时间:2016-07-04 06:42:03

标签: javascript constructor this undefined

我希望了解以下代码的日志返回的明显差异。我希望它们是等价的,不会返回undefined。但是,一个确实返回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 )

1 个答案:

答案 0 :(得分:4)

因为使用普通函数,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 ) ) );
    // ^^^^^^^^^^^
    

    绑定函数忽略调用它的this,而不是使用绑定它的this

  3. 定义变量并将其设置为var me = this; // The variable console.log( floors.find( function ( floor ) { return floor.number === me.floor; // ^^ } ) ); ,然后在回调中使用该变量:

    this
  4. 从ES2015开始,您可以使用箭头功能,它会关闭定义它的上下文的{};在您的情况下,您可以使用简明表单而不使用console.log( floors.find( floor => floor.number === this.floor ) );

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

    或者这是更长的形式:

    server {
            listen       443 ssl;
            server_name  YOUR_SERVER;
            ssl on;
            ssl_certificate /path/to/FILE.crt;
            ssl_certificate_key /path/to/FILE.key;
        }
    
相关问题