2013-06-29 14:14:10 +04:00
---
language: javascript
2013-09-03 08:33:53 +04:00
contributors:
- ["Adam Brenecki", "http://adam.brenecki.id.au"]
2014-03-11 01:23:49 +04:00
- ["Ariel Krakowski", "http://www.learneroo.com"]
2013-09-03 08:33:53 +04:00
filename: javascript.js
2013-06-29 14:14:10 +04:00
---
2014-01-22 09:22:24 +04:00
JavaScript was created by Netscape's Brendan Eich in 1995. It was originally
2014-06-11 03:54:32 +04:00
intended as a simpler scripting language for websites, complementing the use of
2013-06-30 12:03:10 +04:00
Java for more complex web applications, but its tight integration with Web pages
and built-in support in browsers has caused it to become far more common than
Java in web frontends.
2013-06-29 14:14:10 +04:00
2013-07-04 14:19:35 +04:00
JavaScript isn't just limited to web browsers, though: Node.js, a project that
provides a standalone runtime for Google Chrome's V8 JavaScript engine, is
becoming more and more popular.
2015-10-28 05:56:24 +03:00
JavaScript has a C-like syntax, so if you've used languages like C or Java,
a lot of the basic syntax will already be familiar. Despite this, and despite
the similarity in name, JavaScript's object model is significantly different to
Java's.
2013-07-04 20:24:21 +04:00
```js
2015-10-28 05:56:24 +03:00
// Single-line comments start with two slashes.
/* Multiline comments start with slash-star,
2013-06-29 14:14:10 +04:00
and end with star-slash */
// Statements can be terminated by ;
doStuff();
// ... but they don't have to be, as semicolons are automatically inserted
// wherever there's a newline, except in certain cases.
doStuff()
2013-11-26 11:58:44 +04:00
// Because those cases can cause unexpected results, we'll keep on using
// semicolons in this guide.
2013-06-29 14:14:10 +04:00
2013-07-04 20:24:21 +04:00
///////////////////////////////////
// 1. Numbers, Strings and Operators
2013-06-29 14:14:10 +04:00
2014-01-22 09:52:07 +04:00
// JavaScript has one number type (which is a 64-bit IEEE 754 double).
2014-10-28 10:11:59 +03:00
// Doubles have a 52-bit mantissa, which is enough to store integers
2015-10-28 05:57:48 +03:00
// up to about 9✕10¹⁵ precisely.
2013-08-15 15:35:27 +04:00
3; // = 3
1.5; // = 1.5
2013-06-29 14:14:10 +04:00
2014-10-28 10:11:59 +03:00
// Some basic arithmetic works as you'd expect.
2013-08-15 15:35:27 +04:00
1 + 1; // = 2
2014-10-30 18:43:49 +03:00
0.1 + 0.2; // = 0.30000000000000004
2013-08-15 15:35:27 +04:00
8 - 1; // = 7
10 * 2; // = 20
35 / 5; // = 7
2013-06-29 14:14:10 +04:00
2013-06-30 12:14:25 +04:00
// Including uneven division.
2013-08-15 15:35:27 +04:00
5 / 2; // = 2.5
2013-06-29 14:14:10 +04:00
2015-10-18 05:21:25 +03:00
// And modulo division.
10 % 2; // = 0
30 % 4; // = 2
18.5 % 7; // = 4.5
2013-07-03 09:51:03 +04:00
// Bitwise operations also work; when you perform a bitwise operation your float
// is converted to a signed int *up to* 32 bits.
2013-08-15 15:35:27 +04:00
1 < < 2 ; / / = 4
2013-07-03 09:51:03 +04:00
2013-07-04 14:19:35 +04:00
// Precedence is enforced with parentheses.
2013-08-15 15:35:27 +04:00
(1 + 3) * 2; // = 8
2013-06-29 14:14:10 +04:00
2013-06-30 12:14:25 +04:00
// There are three special not-a-real-number values:
2013-08-15 15:35:27 +04:00
Infinity; // result of e.g. 1/0
-Infinity; // result of e.g. -1/0
2015-10-08 05:22:12 +03:00
NaN; // result of e.g. 0/0, stands for 'Not a Number'
2013-06-30 12:14:25 +04:00
2013-06-29 14:14:10 +04:00
// There's also a boolean type.
2013-08-15 15:35:27 +04:00
true;
false;
2013-06-29 14:14:10 +04:00
// Strings are created with ' or ".
2013-08-15 15:35:27 +04:00
'abc';
"Hello, world";
2013-06-29 14:14:10 +04:00
// Negation uses the ! symbol
2013-08-15 15:35:27 +04:00
!true; // = false
!false; // = true
2013-06-29 14:14:10 +04:00
2014-10-27 07:43:20 +03:00
// Equality is ===
1 === 1; // = true
2 === 1; // = false
2013-06-29 14:14:10 +04:00
2014-10-27 07:43:20 +03:00
// Inequality is !==
1 !== 1; // = false
2 !== 1; // = true
2013-06-29 14:14:10 +04:00
// More comparisons
2013-08-15 15:35:27 +04:00
1 < 10 ; / / = true
1 > 10; // = false
2 < = 2; // = true
2 >= 2; // = true
2013-06-29 14:14:10 +04:00
// Strings are concatenated with +
2013-08-15 15:35:27 +04:00
"Hello " + "world!"; // = "Hello world!"
2013-06-29 14:14:10 +04:00
2015-10-29 00:25:44 +03:00
// ... which works with more than just strings
"1, 2, " + 3; // = "1, 2, 3"
"Hello " + ["world", "!"] // = "Hello world,!"
2013-06-29 14:14:10 +04:00
// and are compared with < and >
2013-08-15 15:35:27 +04:00
"a" < "b"; // = true
2013-06-29 14:14:10 +04:00
2014-10-27 07:43:20 +03:00
// Type coercion is performed for comparisons with double equals...
2013-08-15 15:35:27 +04:00
"5" == 5; // = true
2014-10-27 07:43:20 +03:00
null == undefined; // = true
2013-06-29 14:14:10 +04:00
2013-06-30 12:14:25 +04:00
// ...unless you use ===
2013-08-15 15:35:27 +04:00
"5" === 5; // = false
2015-10-18 05:21:25 +03:00
null === undefined; // = false
2013-06-29 14:14:10 +04:00
2014-10-28 10:56:12 +03:00
// ...which can result in some weird behaviour...
13 + !0; // 14
"13" + !0; // '13true'
2015-02-04 01:31:44 +03:00
// You can access characters in a string with `charAt`
2014-03-11 01:23:49 +04:00
"This is a string".charAt(0); // = 'T'
2015-02-04 01:31:44 +03:00
// ...or use `substring` to get larger pieces.
2014-03-11 01:23:49 +04:00
"Hello world".substring(0, 5); // = "Hello"
2015-02-04 01:31:44 +03:00
// `length` is a property, so don't use ().
2014-03-11 01:23:49 +04:00
"Hello".length; // = 5
2013-06-29 14:14:10 +04:00
2015-02-04 01:31:44 +03:00
// There's also `null` and `undefined` .
null; // used to indicate a deliberate non-value
2013-11-05 06:17:58 +04:00
undefined; // used to indicate a value is not currently present (although
2015-02-04 01:31:44 +03:00
// `undefined` is actually a value itself)
2013-06-30 12:14:25 +04:00
2013-11-05 06:17:58 +04:00
// false, null, undefined, NaN, 0 and "" are falsy; everything else is truthy.
2013-06-30 12:14:25 +04:00
// Note that 0 is falsy and "0" is truthy, even though 0 == "0".
2013-06-29 14:14:10 +04:00
2013-07-04 20:24:21 +04:00
///////////////////////////////////
// 2. Variables, Arrays and Objects
2013-06-29 14:14:10 +04:00
2015-02-04 01:31:44 +03:00
// Variables are declared with the `var` keyword. JavaScript is dynamically
// typed, so you don't need to specify type. Assignment uses a single `=`
// character.
2013-08-15 15:35:27 +04:00
var someVar = 5;
2013-06-29 14:14:10 +04:00
2015-10-28 05:47:03 +03:00
// If you leave the var keyword off, you won't get an error...
2013-08-15 15:35:27 +04:00
someOtherVar = 10;
2013-06-29 14:14:10 +04:00
2013-06-30 12:18:50 +04:00
// ...but your variable will be created in the global scope, not in the scope
// you defined it in.
// Variables declared without being assigned to are set to undefined.
2013-08-15 15:35:27 +04:00
var someThirdVar; // = undefined
2013-06-29 14:14:10 +04:00
2015-10-28 05:56:24 +03:00
// If you want to declare a couple of variables, then you could use a comma
2015-10-15 23:38:44 +03:00
// separator
var someFourthVar = 2, someFifthVar = 4;
2013-06-30 13:27:40 +04:00
// There's shorthand for performing math operations on variables:
2013-08-15 15:35:27 +04:00
someVar += 5; // equivalent to someVar = someVar + 5; someVar is 10 now
someVar *= 10; // now someVar is 100
2013-06-30 13:27:40 +04:00
// and an even-shorter-hand for adding or subtracting 1
2013-08-15 15:35:27 +04:00
someVar++; // now someVar is 101
someVar--; // back to 100
2013-06-30 13:27:40 +04:00
2013-06-29 15:39:19 +04:00
// Arrays are ordered lists of values, of any type.
2013-08-15 15:35:27 +04:00
var myArray = ["Hello", 45, true];
2013-06-30 13:27:40 +04:00
// Their members can be accessed using the square-brackets subscript syntax.
// Array indices start at zero.
2013-08-15 15:35:27 +04:00
myArray[1]; // = 45
2013-06-29 15:39:19 +04:00
2013-10-10 02:03:39 +04:00
// Arrays are mutable and of variable length.
myArray.push("World");
myArray.length; // = 4
2014-03-11 01:23:49 +04:00
// Add/Modify at specific index
myArray[3] = "Hello";
2015-02-04 01:31:44 +03:00
// JavaScript's objects are equivalent to "dictionaries" or "maps" in other
2013-06-29 15:39:19 +04:00
// languages: an unordered collection of key-value pairs.
2013-08-15 15:35:27 +04:00
var myObj = {key1: "Hello", key2: "World"};
2013-06-29 15:39:19 +04:00
// Keys are strings, but quotes aren't required if they're a valid
// JavaScript identifier. Values can be any type.
2013-08-15 15:35:27 +04:00
var myObj = {myKey: "myValue", "my other key": 4};
2013-06-29 15:39:19 +04:00
2013-06-30 13:27:40 +04:00
// Object attributes can also be accessed using the subscript syntax,
2013-08-15 15:35:27 +04:00
myObj["my other key"]; // = 4
2013-06-29 15:39:19 +04:00
// ... or using the dot syntax, provided the key is a valid identifier.
2013-08-15 15:35:27 +04:00
myObj.myKey; // = "myValue"
2013-06-29 15:39:19 +04:00
2013-06-30 12:18:50 +04:00
// Objects are mutable; values can be changed and new keys added.
2013-08-15 15:35:27 +04:00
myObj.myThirdKey = true;
2013-06-29 14:14:10 +04:00
2013-06-30 12:44:53 +04:00
// If you try to access a value that's not yet set, you'll get undefined.
2013-08-15 15:35:27 +04:00
myObj.myFourthKey; // = undefined
2013-06-30 12:44:53 +04:00
2013-07-04 20:24:21 +04:00
///////////////////////////////////
// 3. Logic and Control Structures
2013-06-29 14:28:54 +04:00
2015-02-04 01:31:44 +03:00
// The `if` structure works as you'd expect.
2013-08-15 15:35:27 +04:00
var count = 1;
2013-06-30 13:27:40 +04:00
if (count == 3){
// evaluated if count is 3
2014-01-19 09:40:58 +04:00
} else if (count == 4){
2013-06-30 13:27:40 +04:00
// evaluated if count is 4
} else {
2013-07-03 09:51:03 +04:00
// evaluated if it's not either 3 or 4
2013-06-30 13:27:40 +04:00
}
2015-02-04 01:31:44 +03:00
// As does `while` .
2014-01-19 09:40:58 +04:00
while (true){
2013-06-30 13:27:40 +04:00
// An infinite loop!
}
// Do-while loops are like while loops, except they always run at least once.
2015-02-25 19:03:19 +03:00
var input;
2013-06-30 13:27:40 +04:00
do {
2013-08-15 15:35:27 +04:00
input = getInput();
2013-06-30 13:27:40 +04:00
} while (!isValid(input))
2015-02-04 01:31:44 +03:00
// The `for` loop is the same as C and Java:
2013-07-03 09:51:03 +04:00
// initialisation; continue condition; iteration.
2013-06-30 13:27:40 +04:00
for (var i = 0; i < 5 ; i + + ) {
// will run 5 times
}
2015-10-28 05:47:03 +03:00
// The for/in statement iterates over every property across the entire prototype chain.
2015-10-07 02:51:47 +03:00
var description = "";
2015-10-18 05:21:25 +03:00
var person = {fname:"Paul", lname:"Ken", age:18};
2015-10-09 00:34:03 +03:00
for (var x in person){
2015-10-07 02:51:47 +03:00
description += person[x] + " ";
}
2015-10-28 05:47:03 +03:00
// To only consider properties attached to the object itself
// and not its prototypes, use the `hasOwnProperty()` check.
2015-10-07 05:44:30 +03:00
var description = "";
2015-10-18 05:21:25 +03:00
var person = {fname:"Paul", lname:"Ken", age:18};
2015-10-09 00:34:03 +03:00
for (var x in person){
if (person.hasOwnProperty(x)){
2015-10-07 05:44:30 +03:00
description += person[x] + " ";
}
}
2015-10-28 05:47:03 +03:00
// For/in should not be used to iterate over an Array where the index order
// is important, as there is no guarantee that for/in will return the indexes
// in any particular order.
2015-10-07 05:44:30 +03:00
2013-06-30 13:27:40 +04:00
// & & is logical and, || is logical or
if (house.size == "big" & & house.colour == "blue"){
2013-08-15 15:35:27 +04:00
house.contains = "bear";
2013-06-30 13:27:40 +04:00
}
if (colour == "red" || colour == "blue"){
// colour is either red or blue
}
2013-07-03 09:51:03 +04:00
// & & and || "short circuit", which is useful for setting default values.
2013-08-15 15:35:27 +04:00
var name = otherName || "default";
2013-06-30 13:27:40 +04:00
2014-03-11 01:23:49 +04:00
2015-02-04 01:31:44 +03:00
// The `switch` statement checks for equality with `===` .
2015-10-28 05:47:03 +03:00
// Use 'break' after each case
2015-10-08 05:22:12 +03:00
// or the cases after the correct one will be executed too.
2014-03-11 01:23:49 +04:00
grade = 'B';
switch (grade) {
case 'A':
console.log("Great job");
break;
case 'B':
console.log("OK job");
break;
case 'C':
console.log("You can do better");
break;
default:
console.log("Oy vey");
break;
}
2013-07-04 20:24:21 +04:00
///////////////////////////////////
// 4. Functions, Scope and Closures
2013-06-29 14:28:54 +04:00
2015-02-04 01:31:44 +03:00
// JavaScript functions are declared with the `function` keyword.
2013-07-04 14:19:24 +04:00
function myFunction(thing){
2013-08-15 15:35:27 +04:00
return thing.toUpperCase();
2013-07-04 14:19:24 +04:00
}
2013-08-15 15:35:27 +04:00
myFunction("foo"); // = "FOO"
2013-07-04 14:19:24 +04:00
2013-11-26 11:58:44 +04:00
// Note that the value to be returned must start on the same line as the
2015-02-04 01:31:44 +03:00
// `return` keyword, otherwise you'll always return `undefined` due to
2013-11-26 11:58:44 +04:00
// automatic semicolon insertion. Watch out for this when using Allman style.
2015-10-20 00:00:22 +03:00
function myFunction(){
2013-11-26 11:58:44 +04:00
return // < - semicolon automatically inserted here
2015-10-20 00:00:22 +03:00
{thisIsAn: 'object literal'}
2013-11-26 11:58:44 +04:00
}
myFunction(); // = undefined
2013-07-04 14:19:24 +04:00
// JavaScript functions are first class objects, so they can be reassigned to
// different variable names and passed to other functions as arguments - for
// example, when supplying an event handler:
function myFunction(){
// this code will be called in 5 seconds' time
}
2013-08-15 15:35:27 +04:00
setTimeout(myFunction, 5000);
2013-09-13 14:51:14 +04:00
// Note: setTimeout isn't part of the JS language, but is provided by browsers
// and Node.js.
2013-07-04 14:19:24 +04:00
2015-10-19 18:54:42 +03:00
// Another function provided by browsers is setInterval
function myFunction(){
// this code will be called every 5 seconds
}
2015-10-19 20:42:23 +03:00
setInterval(myFunction, 5000);
2015-10-19 18:54:42 +03:00
2013-08-15 15:03:44 +04:00
// Function objects don't even have to be declared with a name - you can write
// an anonymous function definition directly into the arguments of another.
setTimeout(function(){
2013-07-04 14:19:24 +04:00
// this code will be called in 5 seconds' time
2013-08-15 15:35:27 +04:00
}, 5000);
2013-07-04 14:19:24 +04:00
// JavaScript has function scope; functions get their own scope but other blocks
// do not.
if (true){
2013-08-15 15:35:27 +04:00
var i = 5;
2013-07-04 14:19:24 +04:00
}
2013-08-15 15:35:27 +04:00
i; // = 5 - not undefined as you'd expect in a block-scoped language
2013-07-04 14:19:24 +04:00
// This has led to a common pattern of "immediately-executing anonymous
// functions", which prevent temporary variables from leaking into the global
// scope.
2013-08-05 17:22:53 +04:00
(function(){
2013-08-15 15:35:27 +04:00
var temporary = 5;
2015-10-18 12:46:35 +03:00
// We can access the global scope by assigning to the "global object", which
2015-02-04 01:31:44 +03:00
// in a web browser is always `window` . The global object may have a
2013-07-04 14:19:24 +04:00
// different name in non-browser environments such as Node.js.
2013-08-15 15:35:27 +04:00
window.permanent = 10;
})();
temporary; // raises ReferenceError
permanent; // = 10
2013-07-04 14:19:24 +04:00
// One of JavaScript's most powerful features is closures. If a function is
// defined inside another function, the inner function has access to all the
2013-08-14 11:51:44 +04:00
// outer function's variables, even after the outer function exits.
2013-07-04 14:19:24 +04:00
function sayHelloInFiveSeconds(name){
2013-08-15 15:35:27 +04:00
var prompt = "Hello, " + name + "!";
2013-12-14 17:44:06 +04:00
// Inner functions are put in the local scope by default, as if they were
2015-02-04 01:31:44 +03:00
// declared with `var` .
2013-07-04 14:19:24 +04:00
function inner(){
2013-08-15 15:35:27 +04:00
alert(prompt);
2013-07-04 14:19:24 +04:00
}
2013-08-15 15:35:27 +04:00
setTimeout(inner, 5000);
2013-08-14 11:51:44 +04:00
// setTimeout is asynchronous, so the sayHelloInFiveSeconds function will
// exit immediately, and setTimeout will call inner afterwards. However,
// because inner is "closed over" sayHelloInFiveSeconds, inner still has
2015-02-04 01:31:44 +03:00
// access to the `prompt` variable when it is finally called.
2013-07-04 14:19:24 +04:00
}
2013-08-15 15:35:27 +04:00
sayHelloInFiveSeconds("Adam"); // will open a popup with "Hello, Adam!" in 5s
2013-07-04 14:19:24 +04:00
2013-07-04 20:24:21 +04:00
///////////////////////////////////
// 5. More about Objects; Constructors and Prototypes
2013-06-29 15:39:19 +04:00
2013-06-30 12:44:53 +04:00
// Objects can contain functions.
var myObj = {
2013-06-29 15:39:19 +04:00
myFunc: function(){
2013-08-15 15:35:27 +04:00
return "Hello world!";
2013-06-29 15:39:19 +04:00
}
2013-08-15 15:35:27 +04:00
};
myObj.myFunc(); // = "Hello world!"
2013-06-29 15:39:19 +04:00
2013-06-30 12:44:53 +04:00
// When functions attached to an object are called, they can access the object
2015-02-04 01:31:44 +03:00
// they're attached to using the `this` keyword.
2013-06-29 15:39:19 +04:00
myObj = {
myString: "Hello world!",
myFunc: function(){
2013-08-15 15:35:27 +04:00
return this.myString;
2013-06-29 15:39:19 +04:00
}
2013-08-15 15:35:27 +04:00
};
myObj.myFunc(); // = "Hello world!"
2013-06-29 15:39:19 +04:00
2013-06-30 12:44:53 +04:00
// What this is set to has to do with how the function is called, not where
// it's defined. So, our function doesn't work if it isn't called in the
// context of the object.
2013-08-15 15:35:27 +04:00
var myFunc = myObj.myFunc;
myFunc(); // = undefined
2013-06-29 15:39:19 +04:00
// Inversely, a function can be assigned to the object and gain access to it
2015-02-04 01:31:44 +03:00
// through `this` , even if it wasn't attached when it was defined.
2013-06-29 15:39:19 +04:00
var myOtherFunc = function(){
2013-08-15 15:35:27 +04:00
return this.myString.toUpperCase();
2013-06-29 15:39:19 +04:00
}
2013-08-15 15:35:27 +04:00
myObj.myOtherFunc = myOtherFunc;
myObj.myOtherFunc(); // = "HELLO WORLD!"
2013-06-29 15:39:19 +04:00
2013-12-27 10:50:17 +04:00
// We can also specify a context for a function to execute in when we invoke it
2015-02-04 01:31:44 +03:00
// using `call` or `apply` .
2013-12-27 10:50:17 +04:00
var anotherFunc = function(s){
return this.myString + s;
}
anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!"
2015-02-04 01:31:44 +03:00
// The `apply` function is nearly identical, but takes an array for an argument
// list.
2013-12-27 10:50:17 +04:00
anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!"
2015-02-04 01:31:44 +03:00
// This is useful when working with a function that accepts a sequence of
// arguments and you want to pass an array.
2013-12-27 10:50:17 +04:00
Math.min(42, 6, 27); // = 6
Math.min([42, 6, 27]); // = NaN (uh-oh!)
Math.min.apply(Math, [42, 6, 27]); // = 6
2015-02-04 01:31:44 +03:00
// But, `call` and `apply` are only temporary. When we want it to stick, we can
// use `bind` .
2013-12-27 10:50:17 +04:00
var boundFunc = anotherFunc.bind(myObj);
boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!"
2015-02-04 01:31:44 +03:00
// `bind` can also be used to partially apply (curry) a function.
2013-12-27 10:50:17 +04:00
var product = function(a, b){ return a * b; }
var doubler = product.bind(this, 2);
doubler(8); // = 16
2015-02-04 01:31:44 +03:00
// When you call a function with the `new` keyword, a new object is created, and
2015-10-16 21:41:52 +03:00
// made available to the function via the `this` keyword. Functions designed to be
2013-11-05 06:17:58 +04:00
// called like that are called constructors.
2013-06-29 15:39:19 +04:00
var MyConstructor = function(){
2013-08-15 15:35:27 +04:00
this.myNumber = 5;
2013-06-29 15:39:19 +04:00
}
2013-08-15 15:35:27 +04:00
myNewObj = new MyConstructor(); // = {myNumber: 5}
myNewObj.myNumber; // = 5
2013-06-29 15:39:19 +04:00
2013-06-30 12:44:53 +04:00
// Every JavaScript object has a 'prototype'. When you go to access a property
// on an object that doesn't exist on the actual object, the interpreter will
// look at its prototype.
// Some JS implementations let you access an object's prototype on the magic
2015-03-06 12:42:44 +03:00
// property `__proto__` . While this is useful for explaining prototypes it's not
2013-06-30 12:44:53 +04:00
// part of the standard; we'll get to standard ways of using prototypes later.
var myObj = {
2013-11-03 03:50:29 +04:00
myString: "Hello world!"
2013-08-15 15:35:27 +04:00
};
2013-06-29 15:39:19 +04:00
var myPrototype = {
meaningOfLife: 42,
2013-06-30 12:44:53 +04:00
myFunc: function(){
2013-06-29 15:39:19 +04:00
return this.myString.toLowerCase()
}
2013-11-03 04:30:36 +04:00
};
2013-11-03 03:50:29 +04:00
2013-08-15 15:35:27 +04:00
myObj.__proto__ = myPrototype;
myObj.meaningOfLife; // = 42
2013-06-30 12:44:53 +04:00
// This works for functions, too.
2013-08-15 15:35:27 +04:00
myObj.myFunc(); // = "hello world!"
2013-06-29 15:39:19 +04:00
// Of course, if your property isn't on your prototype, the prototype's
// prototype is searched, and so on.
myPrototype.__proto__ = {
myBoolean: true
2013-08-15 15:35:27 +04:00
};
myObj.myBoolean; // = true
2013-06-29 15:39:19 +04:00
// There's no copying involved here; each object stores a reference to its
// prototype. This means we can alter the prototype and our changes will be
// reflected everywhere.
2013-08-15 15:35:27 +04:00
myPrototype.meaningOfLife = 43;
myObj.meaningOfLife; // = 43
2013-06-30 12:44:53 +04:00
2015-03-06 12:42:44 +03:00
// We mentioned that `__proto__` was non-standard, and there's no standard way to
2013-08-20 02:19:48 +04:00
// change the prototype of an existing object. However, there are two ways to
2013-07-03 09:51:03 +04:00
// create a new object with a given prototype.
2013-06-29 15:39:19 +04:00
2013-06-30 12:44:53 +04:00
// The first is Object.create, which is a recent addition to JS, and therefore
// not available in all implementations yet.
2013-08-15 15:35:27 +04:00
var myObj = Object.create(myPrototype);
myObj.meaningOfLife; // = 43
2013-06-29 15:39:19 +04:00
2013-07-03 09:51:03 +04:00
// The second way, which works anywhere, has to do with constructors.
// Constructors have a property called prototype. This is *not* the prototype of
// the constructor function itself; instead, it's the prototype that new objects
// are given when they're created with that constructor and the new keyword.
2013-10-03 22:02:16 +04:00
MyConstructor.prototype = {
2013-09-20 13:52:00 +04:00
myNumber: 5,
2013-07-03 09:51:03 +04:00
getMyNumber: function(){
2013-09-20 13:47:10 +04:00
return this.myNumber;
2013-07-03 09:51:03 +04:00
}
2013-08-15 15:35:27 +04:00
};
2013-10-03 22:02:16 +04:00
var myNewObj2 = new MyConstructor();
2013-08-15 15:35:27 +04:00
myNewObj2.getMyNumber(); // = 5
2013-09-20 13:52:00 +04:00
myNewObj2.myNumber = 6
myNewObj2.getMyNumber(); // = 6
2013-07-03 09:51:03 +04:00
// Built-in types like strings and numbers also have constructors that create
// equivalent wrapper objects.
2013-08-15 15:35:27 +04:00
var myNumber = 12;
var myNumberObj = new Number(12);
myNumber == myNumberObj; // = true
2013-07-03 09:51:03 +04:00
// Except, they aren't exactly equivalent.
2014-08-09 23:41:12 +04:00
typeof myNumber; // = 'number'
typeof myNumberObj; // = 'object'
2013-08-15 15:35:27 +04:00
myNumber === myNumberObj; // = false
2013-07-03 09:51:03 +04:00
if (0){
// This code won't execute, because 0 is falsy.
}
2015-10-28 06:18:53 +03:00
if (new Number(0)){
// This code will execute, because wrapped numbers are objects, and objects
// are always truthy.
}
2013-06-29 15:39:19 +04:00
2013-07-03 09:51:03 +04:00
// However, the wrapper objects and the regular builtins share a prototype, so
// you can actually add functionality to a string, for instance.
2013-06-29 15:39:19 +04:00
String.prototype.firstCharacter = function(){
2013-08-15 15:35:27 +04:00
return this.charAt(0);
2013-06-29 15:39:19 +04:00
}
2013-08-15 15:35:27 +04:00
"abc".firstCharacter(); // = "a"
2013-06-29 15:39:19 +04:00
2013-07-03 09:51:03 +04:00
// This fact is often used in "polyfilling", which is implementing newer
// features of JavaScript in an older subset of JavaScript, so that they can be
// used in older environments such as outdated browsers.
2013-06-30 12:44:53 +04:00
// For instance, we mentioned that Object.create isn't yet available in all
2013-07-03 09:51:03 +04:00
// implementations, but we can still use it with this polyfill:
if (Object.create === undefined){ // don't overwrite it if it exists
2013-06-30 12:44:53 +04:00
Object.create = function(proto){
// make a temporary constructor with the right prototype
2013-08-15 15:35:27 +04:00
var Constructor = function(){};
Constructor.prototype = proto;
2013-07-03 09:51:03 +04:00
// then use it to create a new, appropriately-prototyped object
2013-08-15 15:35:27 +04:00
return new Constructor();
2013-06-30 12:44:53 +04:00
}
}
2013-06-29 14:14:10 +04:00
```
2013-06-30 12:03:10 +04:00
## Further Reading
2015-10-23 20:14:38 +03:00
The [Mozilla Developer Network][1] provides excellent documentation for
JavaScript as it's used in browsers. Plus, it's a wiki, so as you learn more you
can help others out by sharing your own knowledge.
MDN's [A re-introduction to JavaScript][2] covers much of the concepts covered
here in more detail. This guide has quite deliberately only covered the
JavaScript language itself; if you want to learn more about how to use
JavaScript in web pages, start by learning about the [Document Object Model][3].
[Learn Javascript by Example and with Challenges][4] is a variant of this
reference with built-in challenges.
2013-06-30 13:27:40 +04:00
2015-10-23 20:14:38 +03:00
[JavaScript Garden][5] is an in-depth guide of all the counter-intuitive parts
of the language.
2013-07-04 14:19:35 +04:00
2015-10-23 20:14:38 +03:00
[JavaScript: The Definitive Guide][6] is a classic guide and reference book.
2014-03-11 01:23:49 +04:00
2015-10-27 21:04:34 +03:00
[Eloquent Javascript][8] by Marijn Haverbeke is an excellent JS book/ebook with attached terminal
2015-11-01 02:49:57 +03:00
[Eloquent Javascript - The Annotated Version][9] by Gordon Zhu is also a great derivative of Eloquent Javascript with extra explanations and clarifications for some of the more complicated examples.
[Javascript: The Right Way][10] is a guide intended to introduce new developers to JavaScript and help experienced developers learn more about its best practices.
2015-10-27 21:04:34 +03:00
2015-10-23 20:14:38 +03:00
In addition to direct contributors to this article, some content is adapted from
Louie Dinh's Python tutorial on this site, and the [JS Tutorial][7] on the
Mozilla Developer Network.
2013-07-15 04:06:33 +04:00
2014-03-11 01:23:49 +04:00
2015-10-23 20:14:38 +03:00
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript
[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
[3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core
[4]: http://www.learneroo.com/modules/64/nodes/350
[5]: http://bonsaiden.github.io/JavaScript-Garden/
[6]: http://www.amazon.com/gp/product/0596805527/
[7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
2015-10-27 21:04:34 +03:00
[8]: http://eloquentjavascript.net/
2015-11-01 02:49:57 +03:00
[9]: http://watchandcode.com/courses/eloquent-javascript-the-annotated-version
[10]: http://jstherightway.org/