aboutsummaryrefslogtreecommitdiff
path: root/files/pt-br/web/javascript/reference/errors/cant_access_property/index.html
blob: 7c5c9affa3e1422cd0cbc5483282b9f6f21b4ae7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
---
title: 'TypeError: can''t access property "x" of "y"'
slug: Web/JavaScript/Reference/Errors/Cant_access_property
tags:
  - Erros
  - JavaScript
  - TypeError
translation_of: Web/JavaScript/Reference/Errors/Cant_access_property
---
<div>{{jsSidebar("Errors")}}</div>

<h2 id="Mensagem">Mensagem</h2>

<pre class="syntaxbox">TypeError: Unable to get property {x} of undefined or null reference (Edge)
TypeError: can't access property {x} of {y} (Firefox)
TypeError: {y} is undefined, can't access property {x} of it (Firefox)
TypeError: {y} is null, can't access property {x} of it (Firefox)

Exemplos:
TypeError: x is undefined, can't access property "prop" of it
TypeError: x is null, can't access property "prop" of it
TypeError: can't access property "prop" of undefined
TypeError: can't access property "prop" of null
</pre>

<h2 id="Tipo_de_Erro">Tipo de Erro</h2>

<p>{{jsxref("TypeError")}}.</p>

<h2 id="O_que_deu_errado">O que deu errado?</h2>

<p>O acesso a propriedade foi realizado com um valor {{jsxref("undefined")}} ou {{jsxref("null")}}.</p>

<h2 id="Exemplos">Exemplos</h2>

<h3 id="Casos_inválidos">Casos inválidos</h3>

<pre class="brush: js example-bad">// casos undefined e null, onde o metódo substring não irá funcionar

var foo = undefined;
foo.substring(1); // TypeError: x is undefined, can't access property "substring" of it

var foo = null;
foo.substring(1); // TypeError: x is null, can't access property "substring" of it
</pre>

<h3 id="Corrigindo_o_problema">Corrigindo o problema</h3>

<p>Para corrigir o problema de valores <code>undefined</code> ou <code>null</code>,  você pode usar o operador <a href="/en-US/docs/Web/JavaScript/Reference/Operators/typeof">typeof</a>, como no exemplo abaixo.</p>

<pre class="brush: js">if (typeof foo !== 'undefined') {
  // Agora que sabemos que <em>foo</em> está definida, podemos prosseguir
}</pre>

<h2 id="Veja_também">Veja também</h2>

<ul>
 <li>{{jsxref("undefined")}}</li>
 <li>{{jsxref("null")}}</li>
</ul>