Outros objetos Built-In

Olá meus queridos leitores.
Hoje vamos continuar nossos estudos pelos objetos Built-In e finaliza-los!

Lembrando, eu não cobri todos os objetos Built-In, eu cobri os principais e mais usados. Hoje vamos ver os próximos, let's go!

Objeto Date
Como o nome diz, o objeto Date serve para trabalhar com datas em JavaScript, vamos ao primeiro exemplo:

var d = new Date();
alert(d.toString());

Iniciando o objeto Date sem usar parâmetros nós pegamos a data atual do computador do cliente, usando o toString() conseguimos a data no formato GMT.
Vamos agora a um caso mais expecífico:

var d = new Date();

alert(d.getFullYear()); //ano
alert(d.getMonth()); //mes
alert(d.getDate()); //dia
alert(d.getHours()); //hora
alert(d.getMinutes()); //minutos
alert(d.getSeconds()); //segundos
alert(d.getMilliseconds()); //mili segundos
alert(d.getDay()); //dia da semana

Como visto acima, podemos pegar separadamente cada parte do tempo. O objeto Date é apenas isso mesmo, um problema muito normal é quando a pessoa quer fazer um calendário, o problema é que o JavaScript não da suporte nativo para dizer quantos dias tem o mês atual, mas isso não é nada que não possamos implementar:

Date.prototype.getMonthDays = function() {
var days = [31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

var bisexto = false;
var ano = this.getFullYear();

if ((((ano % 4) == 0) && ((ano % 100) != 0)) || ((ano % 400) == 0)) {
bisexto = true;
}

days[1] = bisexto ? 29 : 28;

var mes = this.getMonth();

return days[mes];
}

var d;
d = new Date();
alert(d.getMonthDays());
d = new Date(2006, 1, 12);
alert(d.getMonthDays());
d = new Date(2006, 0, 3);
alert(d.getMonthDays());

Percebam que podemos criar um objeto date informando a data para o objeto, isso é muito útil em caléndarios principalmente. Uma observação importante é que os mesês começam em 0 e não em 1, então 0 é janeiro, 1 é fevereiro...
Prontinho, agora ao usarmos o método getMonthDays teremos como retorno a quantidade de dias do mês, até que nem foi dificil.

Para terminar, vamos criar um relógio digital usando JavaScript, iremos usar um pouco de DOM dessa vez que já é pra dar um gostinho do próximo artigo (que será sobre DOM):

<html>
<head>
<title>Relógio Virtual - JavaScript Developer</title>
<script type="text/javascript">
var updateTime = function() {
var obj = document.getElementById('relogio');
var date = new Date();
var dateString = date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();

obj.innerHTML = dateString;
setTimeout(updateTime, 1000);
};

window.onload = updateTime;
</script>
</head>
<body>
<div id="relogio"></div>
</body>
</html>

Sem miraculosidades, a função updateTime pega uma referência para o DIV com id relógio (usando o document.getElementById(), vamos ver isso melhor na próxima aula), depois pega a data atual, cria uma string com a hora atual, troca o conteúdo da DIV (usando a propriedade innerHTML) e finalmente manda que ela seja executada novamente após 1 segundo (usando setTimeout()).
Isso é tudo que eu tenho a dizer sobre o objeto Date, vamos ao próximo.

Referência do objeto Date:

Date (Built-in Object)
The Date object provides a wide variety of methods for manipulating dates and times. It is important to remember that Date instances do not contain a “ticking clock” but rather hold a static date value. Internally, the date is stored as the number of milliseconds since the epoch (midnight of January 1, 1970 UTC). This accounts for the prominent role of milliseconds in many Date methods.

Milliseconds, seconds, minutes, hours, and months are enumerated beginning with zero; so, for example, December is month 11. Days are enumerated beginning with 1. Years should always be given using four digits. Modern implementations permit years as much as several hundred thousand years in the past or future, although older implementations often have trouble handling dates before 1970. Many implementations have trouble handling dates before 1 A.D.

Note that Universal Coordinated Time (UTC) is the same as Greenwich Mean Time (GMT).

Constructor
var instanceName = new Date();

var instanceName = new Date(milliseconds);

var instanceName = new Date(stringDate);

var instanceName = new Date(year, month, day [, hrs [, mins [, secs [, ms]]]]);

The first constructor syntax creates a new Date instance holding the current date and time. The second syntax creates an instance holding the date given by the number of milliseconds given in the numeric milliseconds argument. The third syntax attempts to create an instance by converting the string stringDate into a valid date using the parse() method (see under the “Methods” section). The fourth syntax creates an instance according to its numeric arguments. If the optional parameters are omitted, they are filled with zero.

Properties
constructor Reference to the constructor object, which created the object. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)

prototype Reference to the object’s prototype. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)

Methods
getDate() Returns a numeric value indicating the day of the month (1-based). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

getDay() Returns a numeric value indicating the day of the week (0 for Sunday, 1 for Monday, and so on). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

getFullYear() Returns a numeric value indicating the four-digit year. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

getHours() Returns a numeric value indicating the hours since midnight (0-based). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

getMilliseconds() Returns a numeric value indicating the number of milliseconds (0-999). (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

getMinutes() Returns a numeric value indicating the number of minutes (0–59). (IE4+ (JScript 3.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

getMonth() Returns a numeric value indicating the number of months since the beginning of the year (0–11; 0 is January). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

getSeconds() Returns a numeric value indicating the number of seconds (0–59). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

getTime() Returns a numeric value indicating the number of milliseconds since the epoch. Dates before the epoch return a negative value indicating the number of milliseconds before the epoch. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

getTimezoneOffset() Returns a numeric value indicating the difference in minutes between the local time and the UTC. Positive values indicate the local time is behind UTC (for example, in the United States) and negative values indicate the local time is ahead of UTC (for example, in India). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

getUTCDate() Returns a numeric value indicating the day of the month (1-based) using UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

getUTCDay() Returns a numeric value indicating the day of the week (0 for Sunday, 1 for Monday, and so on) according to UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

getUTCFullYear() Returns a numeric value indicating the four-digit year according to UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

getUTCHours() Returns a numeric value indicating the hours since midnight (0-based) according to UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

getUTCMilliseconds() Returns a numeric value indicating the number of milliseconds (0–999) according to UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

getUTCMinutes() Returns a numeric value indicating the number of minutes (0–59) according to UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

getUTCMonth() Returns a numeric value indicating the number of months since the beginning of the year (0–11; 0 is January) according to UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

getUTCSeconds() Returns a numeric value indicating the number of seconds (0–59) according to UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

getYear() Returns the current year minus 1900 or in some cases a four-digit year if the year is greater than 1999. This method is deprecated; use getFullYear() instead. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

getVarYear() Returns the VT_DATE corresponding to the object. For use with interaction with COM or VBScript, but in general should be avoided. (IE4+ (JScript 3.0+))

parse(stringDate) Attempts to parse the date given in the string stringDate and if successful returns the number of milliseconds of the date relative to the epoch. Valid strings are given in Chapter 7 but in general can be any common representation of a date, for example "month/day/year", "month day, year", or "month day, year hh:mm:ss". Unambiguous shorthand (for example, "Dec" for December) is permitted. If the date cannot be parsed, NaN is returned. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1, Static)

setDate(dayOfMonth) Sets the day of the month (1-based) in local time as given by the numeric parameter dayOfMonth. (IE4+ (JScript 3.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

setFullYear(year [, month [, day]]) Sets the date to the year given in the numeric argument year in local time. If the numeric parameters month and day are passed, the month (0-based) and day of the month (1-based) are set as well. If month is greater than 11, the year is incremented accordingly. If day is greater than the number of days in the month, the month is incremented accordingly. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

setHours(hours [, mins [, secs [, ms]]]) Sets the hours (0-based) to the numeric argument given in hours in local time. If the optional parameters are passed, the minutes, seconds, and milliseconds are set accordingly. If any of the parameters is greater than the normal range of values, the date is adjusted accordingly (for example, 60 seconds increments the minutes by one and sets the seconds to zero). (IE4+ (JScript 3.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

setMilliseconds(ms) Sets the milliseconds (0-based) to the numeric argument ms in local time. If ms is greater than 999, the seconds are adjusted accordingly. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

setMinutes(minutes [, secs [, ms]]) Sets the minutes (0-based) to the numeric argument minutes in local time. If numeric arguments secs and ms are supplied, the seconds and milliseconds are set to these values. If any argument is greater than the normal range, appropriate values are incremented accordingly (for example, if secs is 60, the minute is incremented by one and the seconds set to zero). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

setMonth(month [, day]) Sets the month (0-based) to the numeric argument month in local time. If the numeric argument day is supplied, the day of the month (1-based) is set accordingly. If either value is outside of the expected range, the date is adjusted accordingly (for example, if month is 12 the year is incremented and the month is set to zero). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

setSeconds(seconds [, ms]) Sets the seconds (0-based) to the numeric argument seconds in local time. If numeric argument ms is supplied, the milliseconds (0-based) are set accordingly. If either value is outside the expected range, the date is adjusted accordingly (for example, if ms is 1000, then the seconds are incremented and milliseconds set to 0). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

setTime(ms) Sets the date to the date given by the number of milliseconds since the epoch given in ms. Negative values of ms specify dates before the epoch. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

setUTCDate(dayOfMonth) Sets the day of the month (1-based) in UTC as given by the numeric parameter dayOfMonth. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

setUTCFullYear(year [, month [, day]]) Sets the date to the year given in the numeric argument year in UTC. If the numeric parameters month and day are passed, the month (0-based) and day of the month (1-based) are set as well. If month is greater than 11, the year is incremented accordingly. If day is greater than the number of days in the month, the month is incremented accordingly. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

setUTCHours(hours [, mins [, secs [, ms]]]) Sets the hours (0-based) to the numeric argument given in hours in UTC. If the optional parameters are passed, the minutes, seconds, and milliseconds are set accordingly. If any of the parameters is greater than the normal range of values, the date is adjusted accordingly (for example, a value of 60 seconds increments the minutes by one and sets the seconds to zero). (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

setUTCMilliseconds(ms) Sets the milliseconds (0-based) to the numeric argument ms in UTC. If ms is greater than 999, the seconds are adjusted accordingly. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

setUTCMinutes(minutes [, secs [, ms]]) Sets the minutes (0-based) to the numeric argument minutes in UTC. If numeric arguments secs and ms are supplied, the seconds and milliseconds are set to these values. If any argument is greater than the normal range, appropriate values are incremented accordingly (for example, if secs is 60, the minute is incremented by one and the seconds set to zero). (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

setUTCMonth(month [, day]) Sets the month (0 based) to the numeric argument month in UTC. If the numeric argument day is supplied, the day of the month (1-based) is set accordingly. If either value is outside of the expected range, the date is adjusted accordingly (for example, if month is 12, the year is incremented and the month is set to zero). (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

setUTCSeconds(seconds [, ms]) Sets the seconds (0-based) to the numeric argument seconds in UTC. If numeric argument ms is supplied, the milliseconds (0-based) are set accordingly. If either value is outside the expected range, the date is adjusted accordingly (for example, if ms is 1000, then the seconds are incremented and milliseconds set to 0). (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

setYear(year) This method is deprecated; use setFullYear() instead. Sets the year to the numeric value year in local time. The year parameter must be the desired year minus 1900. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

toGMTString() This method is deprecated; use toUTCString() instead. Returns the string representation of the date relative to GMT. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

toLocaleString() Returns the date converted to a string formatted according to local conventions as defined by the operating system. For example, the U.S. uses month/day/year whereas Europe uses day/month/year. The return value is not to be used for computation, but rather for display to the user. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

toString() Returns the date as a string. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)

toUTCString() Returns the date formatted as a string according to UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)

UTC(year, month, day [, hours [, mins [, secs [, ms]]]]) This static method returns a numeric value indicating the number of milliseconds between the epoch and the date given by the numeric parameters. Any parameters outside of their expected range cause the date to be adjusted accordingly. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

valueOf() Returns a numeric value indicating the number of milliseconds difference between the date and the epoch. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)

Support
Supported in IE3+ (JScript 1.0+), Mozilla, N2+ (JavaScript 1.0+), ECMAScript Edition 1.

Notes
The Date object is seriously broken in older browsers. The authors suggest avoiding its use except in the most basic tasks in browsers earlier than IE4 and Netscape 4.

The Date object cannot be enumerated directly using for/in.

Objeto Global

Esse é o objeto mais desconhecido e conhecido ao mesmo tempo, muitos usam ele e nem sabem da sua existência.
O objeto Global é um objeto estático (não pode ser instanciado, você não pode fazer: a = new Global()), e assim só tem métodos estáticos. O objeto global pode ser acesso de qualquer lugar, é até meio complicado falar dele, pois ele não tem nada específico, então eu prefiro falar diretamente de suas constates e métodos:

método eval

Esse talvez sejá o método mais conhecido do objeto Global, muitos que ja mexeram com JavaScript devem te-lo usado.
Para quem não conhece, o eval consegue pegar um string, e executa-la como se fosse código, exemplo:

var a = "alert('codigo a ser executado por eval')";
eval(a);

A variável a contém dentro dela uma string, e o eval executa essa string como se fosse código, veremos bem sua utilidade ao estudar-mos Ajax, pois o melhor padrão atual para transferencia de dados (o JSON), usa diretamente o eval para ler o conteudo.

método parseInt

O método parseInt converte uma string em número, exemplo:

var a = '5';
var b = '6';

alert(a + b);
alert(parseInt(a) + parseInt(b));

constantes

Infinity - contem um valor de infinito (um número quando ultrapassa o limite do javascript)
NaN - Not a Number, constante para calculos erroneos que não retornaram um número
undefined - para variáveis indefinidas

Isso é o principal do Global, o resto eu deixo pela referência:

Global (Built-in Object)
The Global object provides methods and constants that can be used freely anywhere in your scripts. Global is defined to be the globally enclosing context, so this object cannot be instantiated or even directly accessed; its properties and methods are always within the scope of an executing script. Its sole purpose is as a catch-all for globally available methods and constants.

Constructor
This object cannot be instantiated because it defines the global context and thus has no constructor.

Properties
Infinity Constant holding the numeric value Infinity. (IE4+ (JScript 3.0+), N4.06+ (JavaScript 1.3+), MOZ, ECMA Edition 1)

NaN Constant holding the numeric value NaN (not a number). (IE4+ (JScript 3.0+), N4.06+ (JavaScript 1.3+), MOZ, ECMA Edition 1)

undefined Constant holding the value undefined. (IE5.5+ (JScript 5.5+), N4.06+ (JavaScript 1.3+), MOZ, ECMA Edition 1)

Methods
decodeURI(encodedURI) URI-decodes the string encodedURI and returns the decoded string. (IE5.5+ (JScript 5.5+), MOZ/N6+ (JavaScript 1.5+), ECMA Edition 3)

decodeURIComponent(encodedURI) URI-decodes the string encodedURI and returns the decoded string. (IE5.5+ (JScript 5.5+), MOZ/N6+ (JavaScript 1.5+), ECMA Edition 3)

encodeURI(uri) URI-encodes the string uri, treating uri as a full URI. Legal URI characters (for example, the :// after the protocol) are not encoded. Returns the encoded string. (IE5.5+ (JScript 5.5+), MOZ/N6+ (JavaScript 1.5+), ECMA Edition 3)

encodeURIComponent(uriComponent) URI-encodes the string uriComponent and returns the encoded string. All potentially problematic characters (for example, / and ?) are encoded. (IE5.5+ (JScript 5.5+), MOZ/N6+ (JavaScript 1.5+), ECMA Edition 3)

escape(string) URI-encodes string and returns the encoded string. Using the newer encodeURIComponent() is preferable. (IE3+ (JScript 1.0+), N2+ (JavaScript 1.0+), MOZ)

eval(string) Executes string as JavaScript. (IE3+ (JScript 1.0+), N2+ (JavaScript 1.0+), MOZ, ECMA Edition 1)

isFinite(value) Returns a Boolean indicating if the numeric argument value is finite. Returns false if value is NaN. (IE4+ (JScript 3.0+), N4.06+ (JavaScript 1.3+), MOZ, ECMA Edition 1)

isNaN(value) Returns a Boolean indicating if the numeric argument value is NaN. (IE4+ (JScript 3.0+), N3+ (JavaScript 1.1+), MOZ, ECMA Edition 1)

parseFloat(string) Parses string as a floating-point number and returns its value. If string cannot be converted, NaN is returned. (IE3+ (JScript 1.0+), N2+ (JavaScript 1.0+), MOZ, ECMA Edition 1)

parseInt(string) Parses string as an integer and returns its value. If string cannot be converted, NaN is returned. (IE3+ (JScript 1.0+), N2+ (JavaScript 1.0+), MOZ, ECMA Edition 1)

unescape(encodedString) URI-decodes encodedString and returns the decoded string. Using the newer decodeURIComponent() method is preferable. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))

Support
Supported in IE3+ (JScript 1.0+), N2+ (JavaScript 1.0+), Mozilla, ECMAScript Edition 1.

Por hoje é apenas isso, no próximo começaremos o DOM, ai vai ficar mais legal, vamos ver como mexer com elementos html e alguns efeitos simples ;). Até lá.

Só para complementar, quando eu postei sobre objetos eu esqueci de deixar a referência do Object, vou coloca-la abaixo e também vou adiciona-la no post de objetos:

Object (Built-in Object)
Object is the basic object from which all other objects are derived. It defines methods common to all objects that are often overridden to provide functionality specific to each object type. For example, the Array object provides a toString() method that functions as one would expect an array’s toString() method to behave.This object also permits the creation of user-defined objects and instances are quite often used as associative arrays.

Constructor
var instanceName = new Object();

This statement creates a new (generic) object.

Properties
prototype The prototype for the object. This object defines the properties and methods common to all objects of this type. (IE4+ (JScript 3.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)

Methods
hasOwnProperty(property) Returns a Boolean indicating whether the object has an instance property by the name given in the string property. (IE5.5+, MOZ/N6+, ECMA Edition 3)

isPrototypeOf(obj) Returns a Boolean indicating if the object referenced by obj is in the object’s prototype chain. (IE5.5+, MOZ/N6+, ECMA Edition 3)

propertyIsEnumerable(property) Returns a Boolean indicating if the property with the name given in the string property will be enumerated in a for/in loop. (IE5.5+, MOZ/N6+, ECMA Edition 3)

toSource() Returns a string containing a JavaScript literal that describes the object. (MOZ, N4.06+ (JavaScript 1.3+))

toString() Returns the object a string, by default "[object Object]". Very often overridden to provide specific functionality. (IE4+ (JScript 3.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)

unwatch(property) Disables watching of the object’s property given by the string property. (N4 (JavaScript 1.2))

valueOf() Returns the primitive value associated with the object, by default the string "[object Object]". Often overridden to provide specific functionality. (IE4+ (JScript 3.0+), N3+ (JavaScript 1.1+), ECMA Edition 1)

watch(property, handler) Sets a watch on the object’s property given in string property. Whenever the value of the property changes, the function handler is invoked with three arguments: the name of the property, the old value, and the new value it is being set to. The handler can override the setting of the new value by returning a value, which is set in its place. (N4 (JavaScript 1.2))

Support
Supported in IE4+ (JScript 3.0+), MOZ, N2+ (JavaScript 1.0+), ECMAScript Edition 1.

Todos os objetos do JavaScript contém os métodos e propriedades acima, com raras excessões. Falow!

Published: September 29 2006

  • category:
  • tags: