Minggu, 13 Oktober 2013

Xathrya Sabertooth

Xathrya Sabertooth


Object in JavaScript

Posted: 13 Oct 2013 01:26 AM PDT

JavaScript has object. We have cover it a bit and compactly, now we will discuss it deeper.

JavaScript object can be view as two different system. One, we can see object as an associative array (aka hash). It stores key-value pairs. On the other side, objects are used for object-oriented programming, using dot notation to access properties and method.

In modern day, JavaScript object also used as a data format known as JSON (Java Script Object Notation). However that is beyond our scope. We will only speak about JavaScript Object, like it is.

Creating Object

An empty object (you may also read as empty associative array) can be created with one of two syntaxes:

o = new Object()  o = { }

The values will be stored as key-value pair. The “properties” can be assigned or delete using “dot notation”. Unlike static type like C++, we can add or delete properties / method dynamically at need.

var obj = { }           // create empty object  obj.name = 'Xathrya';   // add entry with key 'name' and value 'Xathrya'    alert(obj.name);        // get value by key 'name'    delete obj.name;

We can also use brackets instead of dot. The key is passed as a string.

var obj = { }             // create empty object  obj['name'] = 'Xathrya';  // add entry with key 'name' and value 'Xathrya'    alert(obj['name']);       // get value by key 'name'    delete obj['name'];

Both give same result.

We can also declare an object type, like any OOP language. It is actually a group of key-value pairs. The key-value pairs will act as properties and/or method, enclosed by curly-bracket and written as list separated by comma. The key-value pair is written separated by : (colon) operator. For example:

objectLiteral

Which in turn:

var menuSetup = {      width: 300,      height: 200,      title: "Menu"  }    // same as:    var menuSetup = { }  menuSetup.width = 300;  menuSetup.height = 200;  menuSEtup.title = 'Menu';

It is also possible to create nested object:

var user = {      name: "Xathrya",      id: 13510,      birthdate: {          day: 27,          month: 9,          year: 1991      }  }    alert(user.name);          // "Xathrya"  akert(user.birthdate.day); // 27

Non-Existing Properties

We know that we can fetch property from an object. But if the property does not exist, then undefined is returned. It is the sign for us that the indicated property is undefined, or not exist.

var obj = { }    var value = obj.nonexistant;    alert(value);

So, to check whether the value is defined, we can use following:

if (obj.name !== undefined) {   // strict comparison      alert("I've got a name!");  }

Checking If a Key Exists

To see if a property is defined in object, we can use “in” operator to check it.

"key" in object         // true if key exist

Iterating Over Keys-Values

Iterating a keys-values pair is like using foreach, iterating each element of an object. JavaScript has made a special syntax for..in to do so. This syntax will list object properties, using a “pointer” to point to a properties one at a time.

for (key in obj) {      ... obj[key] ... operated  }

Let’s see how we do it:

var menu = {      width:  300,      height: 200,      title: "Menu"  };    for(var key in menu) {      var val = menu[key];        alert("Key: "+key+" value:"+val);  }

There, the key will enumerate the key inside object menu. The key would be “width”, “height”, “title”.

In theory, the order of iteration over object properties is not guaranteed. In practice, there is a de-facto standard about it.

Object Variables are References

A variable which is assigned to object actually keeps reference to it. That is, a variable stores kind-of pointer to real data.

We can use the variable to change this data, this will affect all other references.

var user = { name: 'Xathrya' };   // user is reference to the object  var obj = user;                   // obj ans user refer to same object  obj.name = 'Sabertooth';          // change data in the object    alert(user.name);                 // now it is 'Sabertooth'

A major drawback is JavaScript have characteristic like Java. The variable is reference, not a value / pointer. Therefore we cannot modify the value of object directly.

function increment(val) {      val++;  }    var val = 5;  increment(val);  alert(val);          // val is still 5

Instead, we can still do this, pass the value inside of a container instead of the reference.

var obj = { val: 5 }  function increment(obj) {      obj.val++;  }    increment(obj)  alert(obj.val);        // obj.val is now 6

The difference is because in first example variable val is changed, while in second example obj is not changed, but data which it references is modified instead.

Properties and Methods

We can store anything in object. Not just a simple value, but also functions. Remember that functions is also key-value pair with value as function.

var car = {      name: "XathCar",      model: 500,      weight: 850,      color: "white",        curSpeed: 0,        start: function() {           alert("Car is started");           this.curSpeed = 0;      }        drive: function() {           alert("Car is running");           this.curSpeed += 10;      }        brake: function() {           alert("A brake is pressed");           this.curSpeed -= 5;      }  };

Here we have functions stored by key ‘start’, ‘drive’, and ‘brake’.

Note the this keyword inside the functions. When a function is called from the object, this become a reference to the object.

To call a method, we can use something like this:

car.start();  car.drive();  car.brake();

To check if a method is exists, we can just check it using if syntax:

if (car.start) car.start();

Constructor

Constructing an object can use new function.

The thing which will be an object should be declared as a function. The function then can have some properties and also some methods. Inside the function, we also have this pointer. Instantiation will take a function name and a keyword new before it.

For example:

function Animal(name) {      this.name = name;      this.canWalk = true;      this.canFly = true;  }    var animal = new Animal("PenQueen");    alert(animal.name);

Which has same result as:

var animal = {      name: "PenQueen",      canWalk: true,      canFly: true  }

If the function returns an object, this is ignored.

function Animal() {      this.name = 'Kitty'      return { name: 'Salamander' }  // <-- will be returned  }    alert( new Animal().name )         // Salamander

Convention speaking: all functions which are meant to create objects with new have uppercased first letter in the name.

If the function don’t take any arguments, we may omit braces.

Built-In Object

The standard library of JavaScript includes a list of built-in objects. They are, for example:

  • Math – provides methods for mathematical computations,
  • Date – for dates,
  • RegExp – for regular expressions.

Function are also objects, instances of the new Function.

For browser, there are also global object / variable such as:

  • Document
  • Window

Compact Tutorial on JavaScript Basic

Posted: 13 Oct 2013 12:03 AM PDT

We will not cover how to program in JavaScript in detail but rather what to do in JavaScript.

Where to Write?

There are some alternatives to write a piece of JavaScript code: inside a document using <script>, inline on HTML tag, external files.

JavaScript can be written on enclosing pair of tag <script> </script>

<script>  alert("My First JavaScript");  </script>

We can write this on any section of HTML document, for example: <body>, <head>, or both. It is a common practice to put code in the <head> section, or at the bottom of the page. This way they are all in one place and do not interfere with page content.

For example, this code is a script embedded to <body> section.

<!DOCTYPE html>  <html>  <body>    <h1>My Web Page</h1>    <p id="demo">A Paragraph</p>    <button type="button" onclick="myFunction()">Try it</button>    <script>  function myFunction()  {  document.getElementById("demo").innerHTML="My First JavaScript Function";  }  </script>    </body>  </html>

JavaScript can be embedded to a HTML tag. For a simple code this approach can be used. Here we modified the above code:

<!DOCTYPE html>  <html>  <body>    <h1>My Web Page</h1>    <p id="demo">A Paragraph</p>    <button type="button" onclick="document.getElementById('demo').innerHTML='My First JavaScript Function'">Try it</button>    </body>  </html>

Last, we can write a JavaScript code in external files and make the HTML file loads them. This way, several web pages can use it. External JavaScript files have the file extension .js.

To include external script, point to the .js file in the “src” attribute of the <script> tag:

<!DOCTYPE html>  <html>  <body>  <script src="myScript.js"></script>  </body>  </html>

Dynamic Type Inference

JavaScript is a scripting language. It is a language which dynamically infer the types of objects, instead of forcing object definition.

For example, in C or C++ you can have a variable which is defined as integer, floating point number, a character, etc. Including user-defined type. When declaring a variable, you have to specify what kind of variable (the type) of it. When you fail to define it, compiler will refuse to process. You should also make sure the type is defined / declared ahead of variable declaration. Here is the example in C++:

int myInt = 9;  float myFloat = 3.14;  char myChar = 'X';

In JavaScript, no such things exists. Instead you can have all defined as a variable, regarding the value.

var myInt = 9;  var myFloat = 3.14;  var myChar = 'x';

Not only primitive type, you can treat object with same manner.

You can also write all variable declaration in one line, separated by comma:

var lastname="Sabertooth", age="21", job="CEO";

or you can span it to multiple lines, but still the declaration is separated by comma:

var lastname="Sabertooth",  age="21",  job="CEO";

Though indentation is not really a matter, it is advised to watch your indentation.

As implication of this behavior, you can assign any value to JavaScript variable. But, in computer programs variable are often declared without no value. The value can be something that will be provided later, like user input. However how we declared an empty variable? Here undefined comes.

The variable carname will have the value undefined after the execution of the following statement:

var carname;

An undefined value is not instance of any type. It is purely declaring the variable as empty.

There is also exists the sibling, null value.

A Statement, Code Blocks

A statements are “commands” to the browsers or interpreters.

A statement can be an expression or simply a function / procedure invocation.Like it’s predecessor, JavaScript can use semicolon ; to separates JavaScript statements. This enables us to write multiple statement on a line. However, write semicolon at the end is optional.

document.write("Xathrya Sabertooth"); document.write(" was here");

The statements are case sensitive. Watch capitalization closely. A function getElementById is not same as getElementByID. A variable named myVariable is not same as MyVariable.Some statements can also be grouped together in blocks. Blocks started with a left curly bracket, and ended with a right curly bracket. Blocks are used for defining function, branching (if-else, switch), repetition (for, do, while), or simply grouping statements.Different in Way of Code

JavaScript also use different paradigm. It is still executed in sequential, means a higher line of code will be executed earlier than code in bottom.

What we means in different paradigm?

Writing JavaScript require ones to know event-driven model. Lot of code or function are act as callback. They are executed when some kind of event has been triggered. The event can vary, such as button click, page load, etc. The event can be associated to specific page element such as button, image, etc.

If you have code in native programming language, for example C/C++, you can feel the difference. In C/C++ you have a main function where all execution alive. In JavaScript, they are persistent and wait for a call. This should be noted!

We Talk About Input/Output

In JavaScript, we can say manipulating I/O is the primary goal. We say input when we grab content of some elements, whether we process it or not. We say output when we write things to document, whether it is processed or not. The output / writing can be create, update, or delete DOM. Remember that JavaScript can manipulate a DOM freely.

I/O can also be considered as communication with other entity, such as remote server in AJAX.

What are Types?

In fact, JavaScript do have types declared. They are strings, number, boolean, and object.

A string is a series of characters. It can be any text inside quotes (single or double quotes). You can also use quotes inside a stirng, as long as they don’t match the start quote.

var carname="Volvo XC60";  var carname='Volvo XC60';  var answer="It's alright";  var answer="He is called 'Johnny'";  var answer='He is called "Johnny"';

A number is a generalization of integer and floating point number. JavaScript also support large number using scientific notation.

var x1=34.00;      // Written with decimals  var x2=34;         // Written without decimals  var y=123e5;      // 12300000  var z=123e-5;     // 0.00123

A boolean is a special type which has only two kind of values: true or false. It is often used in condition testing. We will

var x=true;  var y=false;

JavaScript object is delimited by curly braces. Inside the braces the object’s properties are defined as name and value pairs. The properties are separated by commas. Here is how we write a JavaScript object. Note that we can use one line to define all, or single line to define each.

var person={  firstname : "Xathrya", lastname  : "Sabertooth",  id        :  5566,  company   : "Sakraysoft Nanotech"  };

When we declare an object, we will use following syntax:

var Xathrya = new person;

and addressing the properties by two ways:

name = Xathrya.lastname;  name = Xathrya["lastname"];

You can also create a new object for String, Number, and Boolean respectively.

There is also a type which is defined as a collection of value. This type is called as Array(). Like we predict, JavaScript array is unlike C/C++ array. JavaScript can be any value.

var X = new Array();  X[0] = "Xathrya";  X[1] = "Sabertooth";  X[2] = 13510030;

Operators

Assign

Assign is an operator to assign value to a variable. In other world, it write a value to variable. The operator is =

y = 5;  z = 2;  x = y + z;

The x will be 7.

JavaScript can support C-like assignment operators, using itself as first operand and modify the value with second operand. The operators we talk about are: += (add this with), -= (subtract this with), *= (multiply this with), /= (divide this with), %= (mod this with).

For example:

var X = 10;  X += 2;    // X now 12  X -= 3;    // X now 9  X *= 4;    // X now 36  X /= 3;    // X now 12  X %= 8;    // X now 4

Arithmetic

There are various arithmetic operations supported by JavaScript: + (addition), – (subtraction) , * (multiplication), / (division), % (modulus or division remainder), ++ (increment), — (decrement).

var x = 15;  var y;    y = x + 3;   // y now 15 + 3 = 18  y = x - 4;   // y now 15 - 4 = 11  y = x * 2;   // y now 15 * 2 = 30  y = x / 3;   // y now 15 / 3 = 5  y = x % 9;   // y now 15 % 9 = 6

Overall, the operators are similar to C and derived programming language’s operators.

Comparison

Comparison operators are operators used for comparing value of variable. There are three “state” available in Math: less, equal, greater. From this three states, we can have some comparison: < (less than), <= (less than or equal), == (equal), != (not equal), > (greater than), >= (greater than or equal). JavaScript also expand operators, adding two new operator:  === (exactly equal to), !== (not equal). All operator will return a boolean value, true or false.

So what is the difference of == to === and != to !===?

Remember that JavaScript is resolve type dynamically. The === means both variable have equal value and equal type. While the !== means the variable has different value or different type.

Here is the example:

var x = 5;    x == 8;      // false  x == 5;      // true    x === "5";   // false  x === 5;     // true    x != 8;      // true    x !== "5";   // true  x !== 5;     // false    x > 8;       // false    x < 8;       // true    x >= 8;      // false    x <= 5;      // true

This operator can be used to evaluate a condition.

String operation

Operator + can also be used to string. It will concatenate two string and produce new string.

txt1 = "Xathrya ";  txt2 = "Sabertooth";  txt3 = txt1 + txt2;    // txt3 = "Xathrya Sabertooth"

When you adding two number, a new summed value will be returned. However, when you “add” string and a number, it will produce a string:

x = 5 + 5;         // x = 10  y = "5" + 5;       // y = "55"  z = "Hello" + 5;   // z = "Hello5"

Logical

These operators act as conjunction to one or more logical expression and then return a boolean value. These operators consists of: && (and), || (or), ! (not).

An && “and” operator need two operand and return true when both expression has value True. In math, it is denoted as ^.

An || “or” operator need two operand and return true unless both expression has value False. In math, it is denoted as v.

A ! not operator need one operand and invert the value. For example if the expression is False, it will produce True. Otherwise, it will product False. In math, it is denoted as ~.

Here we have a complete list:

truthtable

Introduction to JavaScript

Posted: 12 Oct 2013 06:39 PM PDT

JavaScript, standardized as ECMAScript, is a popular language especially when you want to build a web-based application. JavaScript is (not only) the programming language of the web, though we will discuss it why we say not only. In modern day, all modern web browsers – on desktop, game consoles, tablets, and smart phones – ship JavaScript interpreters. This makes JavaScript the most ubiquitos programming language in history.

While HTML (and HTML5) acts just as a skeleton and CSS3 act as decorator, JavaScript do the logic in client side. It is used to specify the behavior of a web page.

If you are already familiar with other programming language, you should be able to learn JavaScript quickly. However, we should note something about JavaScript: JavaScript use unique programming model. JavaScript also has nothing to do with Java programming language. They are different in concept and design.

JavaScript is a Script

JavaScript is a scripting language. That means, JavaScript cannot run without an interpreter. Here we know what the interpreters are: browsers.

A scripting language is a lightweight programming language. In client-side scripting, JavaScript is code inserted into HTML pages or load by page.

What Can JavaScript Do?

In a browser, JavaScript can construct a behavior for a web page. It can manipulate a web page in some manners defined by a programmer. It can add, delete, and change a HTML object (also known as DOM or Document Object Model). It can also change the style of element (button, etc).

JavaScript can also used as a callback. This way, when a specific event occurred, such as a button clicked, a JavaScript code can be executed. For example: when user filling a form and then click a ‘Register’ button, javascript then check the validity all the data.

In some page, a page can communicate asynchronously to server to update specific content without refreshing the page. This is called AJAX, a more advance use of JavaScript. Using this, we can create an interactive web-app.

JavaScript on Other Platform

JavaScript still a script and need an interpreter. However, this day we can see more interpreter aside of browsers. On a desktop, we have NodeJS which is another implementation of JavaScript. NodeJS allows us to write and execute JavaScript like other scripting language (i.e. Python, Ruby, Perl). On some level, JavaScript (subset) is also used to create a interactive application.

All possibility open for JavaScript.

Tidak ada komentar:

Posting Komentar