Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you have to use keyword "this" instead of class name?

this is code from a react.js tutorial and the "this" keyword represents the App class. So my question is why can I not just write the class name instead?

import React, { Component } from 'react';
import './App.css';
import Person from './Person/Person';

class App extends Component {

state = {
 persons: [
  { name: 'Max', age: 28 },
  { name: 'Manu', age: 29 },
  { name: 'Stephanie', age: 26 }
 ]
}

render() {
 return (
  <div className="App">
    <h1>Hi, I'm a React App</h1>
    <p>This is reallyyyyyyyy working!</p>
    <button> switch name</button>
    <Person name={App.state.persons[0].name} age={this.state.persons[0].age} />
    <Person name={this.state.persons[1].name} age={this.state.persons[1].age}>My Hobbies: Racing</Person>
    <Person name={this.state.persons[2].name} age={this.state.persons[2].age} />
  </div>
 );
// return React.createElement('div', {className: 'App'}, 
React.createElement('h1', null, 'Hi, I\'m a React App!!!'));
}
}

export default App;
like image 446
Ryder Thacker Avatar asked Sep 12 '25 18:09

Ryder Thacker


2 Answers

Because in JavaScript, when you specify a class name (in particular, inside a class), you get a reference to the class, not to the current class instance. The instance properties and methods are not available through its class. Meanwhile this represents the current instance.

class App {
    test() {
        console.log(App); // "class App ..."
        console.log(this); // "[object Object]"
        console.log(App.foo()); // "1"
        console.log(this.foo()); // "2"
        console.log(this.constructor.foo()); // "1"; this.constructor is a reference to the current object class
    }

    static foo() {
        return 1;
    }

    foo() {
        return 2;
    }
}
like image 50
Finesse Avatar answered Sep 15 '25 08:09

Finesse


Because

The this keyword refers to the current instance of the class. It can be used to access members from within constructors, instance methods, and instance accessors.

This rule is followed by any Object Oriented programming language. However, If you force your class to take instance with its name then it has to be static (Not the class itself but properties and methods).

For your purpose we can create App class as module

class App {
  hello() { return 'Hello World'; }
}

export let AppInstance = new App ();

Usage

import { AppInstance } from './App';
AppInstance.hello();
like image 32
Manoz Avatar answered Sep 15 '25 08:09

Manoz