LoginSignup
0
0

More than 1 year has passed since last update.

Reactの学ぶ日記#1 This is a Instance

Last updated at Posted at 2021-12-11

今はReactのComponentを学んでいる:

class Tapioka extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        name: 'tapioka'
        tea: 'black tea',
        mate: 'creamer',  
        sugar: 100%,
        ice: 100%,
    };
  }

  render() {
    return <p>{this.state.name}にきめた!</p>;
  }
}

ReactDOM.render(<Tapioka />, document.getElementById('app'));

React.ComponentはReactが提供するparent classである。上記のTapiokaというchild classように、様々なcomponentsがclassで作れる。React.Componentはthisを頻繁に使っているので、僕はthisを理解するために、OOPとJavaScriptの歴史を少し勉強した。

簡単に理解すると、OOPでthisはclassのinstance。そして、classと関係ない場合だけではなく、thisはどこでも使える。場合によって、thisは意味がない時もある。

たとえば、以下の場合、sloppy modeで、thisはwindowになる。

function whatIsThis() {
    console.log(this);
}

whatIsThis(); //window 

Strict modeなら、thisはundefined。

'use strict';

function whatIsThis() {
    console.log(this);
}

whatIsThis(); //undefined

僕はstrict modeでのthisはsloppy modeより合理的と思う。

// ところで、thisは他の言語より自由に使えるのもJavaScriptの特性だね(笑)。
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0