在打字稿中确定范围

时间:2018-01-29 04:43:00

标签: node.js typescript scope

我在nodeJs中创建了一个示例应用程序,它使用pg-promise在Postgres中执行查询。并用一个名为PostgresDataAccess的类包装它。在下面的代码中,为什么我无法访问" dal"来自我的get和getOne函数的对象。 "这"关键字返回undefined。有人可以解释一下吗?

 <?php

$servername = 'localhost';
$username = '********';
$password = '*****';
$dbname = '********';

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error){
    trigger_error("Connection failed: " . $conn->connect_error);
} 



if (isset($_REQUEST['mailsend'])){
    $firstname  = $_POST['FirstName'];
    $email      = $_POST['email'];
    $number     = $_POST['number'];
    $query      = $_POST['query'];


    $to = "enter_your@email.com";  //enter your mail id here
    $tosec = "second_email@here.com";  //enter your second mail id here



  $subject = "A New Query";

 $message = "Name:" .$firstname. "\r\n";
 $message .=" Email:" .$email.  "\r\n" ; 
 $message .= "Mobile Number:" .$number. "\r\n"; 
 $message .= "Query:" .$query. "\r\n"; 


 //print_r($message);

    $return = mail($to,$subject,$message);
    $returnsec = mail($tosec,$subject,$message);        


if($retrun && $returnsec){  
    $sql = "INSERT INTO query SET 
      `name` = '{$firstname}',
      `email` = '{$email}',
      `phone` = '{$number}',
      `query` = '{$query}'";

    if ($conn->query($sql) === TRUE) {
        echo "<script>alert('Your Message Sent Sucessfully, We will contact you soon.');</script>";
    }else{
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
  }
 } ?>

1 个答案:

答案 0 :(得分:2)

  

为什么我无法从get和getOne函数访问“dal”对象。 “this”关键字返回undefined

更改:

get(req: Request, res: Response, next: NextFunction) {
  let projects = this.dal.queryDb('select * from projects', null, res);
}

get = (req: Request, res: Response, next: NextFunction) => {
  let projects = this.dal.queryDb('select * from projects', null, res);
}

作为arrow functions preserve this

getOne相同。