0

Thanks guys, this turned out to be my own confusion about the grammar of ES6 class.

But I asked this question because I encountered the following problem.

I was learning React and I have the following snippet of code.

import React, { Component } from 'react';

class SearchBar extends Component {
constructor(props){
    super(props);
}

render() {
    // console.log(this);
    return <div>
            <input
                onChange={ this.onInputChange }
            />
        </div>;
    }

    onInputChange(event) {
        console.log(this);
    }
}

export default SearchBar;

Fairly simple, this code will generate an input component and when things within it changes, we log out 'this'.

However, this code will generate 'undefined' all the time.

As I know that 'this' within the object child function should point to object itself, why this is happening?

By the way, the main js file looks like this.

import ReactDOM from 'react-dom';
import React from 'react';

import SearchBar from './components/search_bar';

const API_KEY = 'AIzaSyCdAXs0YXxqGUKjb4sZsmsF_hHq_f3PJmY';

const App = () => {
    return (
            <div>
            <SearchBar />
            </div>
            );
}

ReactDOM.render(<App />, document.querySelector('.container'));

And the html looks like this

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="/style/style.css">
    <link rel="stylesheet" href="https://cdn.rawgit.com/twbs/bootstrap/48938155eb24b4ccdde09426066869504c6dab3c/dist/css/bootstrap.min.css">
    <script src="https://maps.googleapis.com/maps/api/js"></script>
  </head>
  <body>
    <div class="container"></div>
  </body>
  <script src="/bundle.js"></script>
</html>

where bundle.js is the output react script with bable.

W.Chen
  • 407
  • 1
  • 4
  • 6
  • Because you are using prototypical inheritance – Hosar Feb 24 '17 at 06:08
  • 2
    The value of `this` within a function depends on how that function was called. In over-simplified terms, if you call a function using "dot" notation like `tester.hello()` then within the function `this` will be set to the object to the left of the `.` - in your case that is `tester`. This is a duplicate, but i think [the MDN page on `this`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this) explains it better than the other question's accepted answer. – nnnnnn Feb 24 '17 at 06:09

1 Answers1

1

this keyword points to object that named test because of the prototype. hello function is not a seperated function from test object.

If you ask why use prototype?

Using the prototype makes for faster object creation, since that function does not have to be re-created each time a new object is created.