Javascript typeerror this is undefined

What am i doing wrong? TypeError: this is undefined

when trying to change the state. I wrote name: ‘hello’, to just change the state to something an visualize in the form if it is working. Same as ‘TryDescription’.

export default class Posts extends Component < constructor(props)< super(props); this.state = < error: null , posts: [], isLoaded: false, name : null, description: null, >> static handleSubmit(event)< event.preventDefault(); console.log('hello'); >; handleInputchange(event)< console.log(event.target.value); this.setState(< error : null , posts: [] , isLoaded:false, name:'Hello', description: 'TryDescription', >) >; render() < const < error, isLoaded, posts , name , description >= this.state; return ( 
>

The name is: type="text" name='name' className="form-control" placeholder="Tittle"/>

The description is: name="description" type="text" className="form-control" placeholder="Description"/>

>
>>
Subtítulo

Card link Another link

)>
) >

Источник

Why is «this» undefined in this class method?

I’ve tried to search over what seems to be the entire internet, but I’m still vexed by a problem with a JS class I’m writing for a Micro Service (still in learning a bit). So, I try to call a class method on an instantiated object, and according to my knowledge and my (faulty I presume) unit tests it should work. Well, I’ll start with the error I receive:

 GET /api/users 500 2.863 ms - 2649 TypeError: Cannot read property 'repository' of undefined at list (C:\Users\\Documents\Programming\node\kaguwa-ngn\kaguwa-user-service\controllers\user-controller.js:20:9) at Layer.handle [as handle_request] (C:\Users\\Documents\Programming\node\kaguwa-ngn\kaguwa-user-service\node_modules\express\lib\router\layer.js:95:5) at next (C:\Users\\Documents\Programming\node\kaguwa-ngn\kaguwa-user-service\node_modules\express\lib\router\route.js:137:13) 
user-controller.js 'use strict'; var utils = require('./utils'); class UserController < constructor(repository) < this.repository = repository || <>; > /** * * Lists all users. * * @param req * @param res */ list(req, res) < this.repository.list(function (err, users) < if (err) return res.status(500).json(utils.createError(500)); if (Object.keys(users).length !== 0) < res.json(users); >else < res.status(404).json(utils.createNotFound('user', true)); >>); > // more code > module.exports = UserController 
user-api.js 'use strict'; var express = require('express'); var UserController = require('../controllers/user-controller'); var router = express.Router(); module.exports = function (options) < var userController = new UserController(options.repository); router.get('/users', userController.list); // Mode code return router; >; 

I really jave no idea on why this undefined in UserController . Any help would be greatly appriciated.

Источник

React TypeError: this is undefined [дубликат]

Вообщем задача такая: написать компонент который будет возвращать тэг p и менять цвет при клике курсором на него. Я написал следующий компонент:

class Rgb extends React.Component < constructor (props) < super(props); this.state = < color: "red" >; > Cklicker () < if (this.state.color == "red") this.setState(< color: "green" >); if (this.state.color == "green") this.setState(< color: "blue" >); if (this.state.color == "blue") this.setState(< color: "red" >); > render () < return (

style=>RGB

); > >

Но при нажатий вместо того что бы поменять цвет возникает ошибка: TypeError: this is undefined Cklicker

 133 | > 134 | Cklicker () 135 | < >136 | if (this.state.color == "red") this.setState(< color: "green" >); 137 | ^ if (this.state.color == "green") this.setState(< color: "blue" >); 138 | if (this.state.color == "blue") this.setState(< color: "red" >); 139 | > 

2 ответа 2

React не устанавливает контекст для обработчиков событий. Добавьте this.Clicker = this.Clicker.bind(this) в конструктор.

Либо используй стрелочные функции. Они привязывают текущий контекст к функции.

Связанные

Похожие

Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.7.21.43541

Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

Источник

Javascript Objects — «this» is undefined?

I am writing some Javascript for a Change Calculator exercise. One of the requirements is to use object constructors; however, I am having a lot of trouble accessing a property in my object, from within one of the object’s methods. Here is my object:

function Coin(intValue)< this.intCents = null; //The property function setCents(intValue) < //Trying access the intCents property from within this method /// Sets the intCents property for this object. If the given value is invalid, then the intCents property is given NaN. /// The new intCents value. if (isValid(intValue)) < this.intCents = intValue; //---javascript bugs out here!--- >else < console.error("Invalid value given to Coin Object."); this.intCents = NaN; >> setCents(intValue); function getCents() < /// Returns the value of intCents. /// The intCents value. return this.intCents; > > 
var objCoin; var calculateChange = function () < if (objCoin != null) < objCoin.setCents(Number.parseInt("67")); >else < objCoin = new Coin(Number.parseInt("67")); >> 

enter image description here

I took out some unnecessary code, but overall the basic functionality goes as following: User enters a number in a textbox and then clicks a button on a webpage. The button calls calculateChange method through the onclick event. Inside the calculateChange method where «67» is, would normally be some code to get the textbox value. To simplify the code and provide a specific example of what type of value would be passed in, I replaced it with the «67». What is post to happen is, assuming the user enters an integer. If my objCoin variable is not instantiated with a Coin instance, then create a new instance and pass in the user’s input through the Coin’s constructor. If my objCoin is instantiated, then use the setCents method to hold the user’s input. Here is an screenshot showing what is happening and where the javascript bugs out: From my understanding, the issue appears to be with the «this» key word, as it is apparently undefined in if-statement. Despite this, I don’t see anything wrong with my code. From what I understand in my classes, this.intCents = null; is the correct way to create a property for the Coin object, and this.intCents would be the correct way to refer to the property from within the object regardless of where exactly in the object it is. I tried reading up on the following questions: ‘this’ is undefined in JavaScript class methods seems to talk more about the new keyword and accessing properties from already created objects. How does the «this» keyword work? had a lot of interesting example; however, I still don’t see the flaw in my code. Where am I going wrong with accessing the intCents property? What is this in this scenario? (I believe it’s object variable objCoin) Programs Used: Visual Studio 2015 Enterprise Google Chrome and its Developer Tools

Источник

Why is ‘this’ undefined inside class method when using promises? [duplicate]

I have a javascript class, and each method returns a Q promise. I want to know why this is undefined in method2 and method3 . Is there a more correct way to write this code?

function MyClass(opts) < this.options = opts; return this.method1() .then(this.method2) .then(this.method3); >MyClass.prototype.method1 = function()< // . q stuff. console.log(this.options); // logs "opts" object return deferred.promise; >; MyClass.prototype.method2 = function(method1resolve)< // . q stuff. console.log(this); // logs undefined return deferred.promise; >; MyClass.prototype.method3 = function(method2resolve)< // . q stuff. console.log(this); // logs undefined return deferred.promise; >; 

When you use bind() it creates another function with exactly the scope you will pass by params. Although It answers just your last question, take a look at the Mozila’s documentation: developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/…

In 8 words, explain how the heck is this a duplicate of that? I just had this exact same question come up, which would not have been answered by that. I know that already, but I’m coming to terms with promises, ES6 Classes, and this .

@Paulpro not so sure this should be marked as a duplicate of the setTimeout issue; as the problem arises in two completely different ways. People looking to resolve their this scoping issues in the context of promises are immediately being pointed to a more indirect question, where the accepted answer uses anti-patterns from 2009. 2 + 2 = 4 !== ((8+2)*6)/15 = 4

IMO definitely shouldn’t be marked as a duplicate especially to a question about timeouts. This question specifically about Promises and the answers are a god send. Thank you.

4 Answers 4

this is always the object the method is called on. However, when passing the method to then() , you are not calling it! The method will be stored somewhere and called from there later. If you want to preserve this , you will have to do it like this:

or if you have to do it the pre-ES6 way, you need to preserve this before:

var that = this; // . .then(function() < that.method2() >) 

FAR FAR easyer way: .then(( foo = this) => <. //then use foo instead of this [also translates to the pre-es6 version] Just make sure it's not overwridden!

Promise handlers are called in the context of the global object ( window ) by default. When in strict mode ( use strict; ), the context is undefined . This is what’s happening to method2 and method3 .

;(function()< 'use strict' Promise.resolve('foo').then(function()); // undefined >()); ;(function()< Promise.resolve('foo').then(function()); // window >()); 

For method1 , you’re calling method1 as this.method1() . This way of calling it calls it in the context of the this object which is your instance. That’s why the context inside method1 is the instance.

Basically, you’re passing it a function reference with no context reference. The this context is determined in a few ways:

  1. Implicitly. Calling a global function or a function without a binding assumes a global context.*
  2. By direct reference. If you call myObj.f() then myObj is going to be the this context.**
  3. Manual binding. This is your class of functions such as .bind and .apply . These you explicitly state what the this context is. These always take precedence over the previous two.

In your example, you’re passing a function reference, so at it’s invocation it’s implied to be a global function or one without context. Using .bind resolves this by creating a new function where this is explicitly set.

*This is only true in non-strict mode. In strict mode, this is set to undefined .

**Assuming the function you’re using hasn’t been manually bound.

Источник

Читайте также:  Left string in javascript
Оцените статью