Ok this tutorial will summarize the core features of Javascript in comparison with other OOPs.
1/ Why is Javascript?
a. Javascript (JS) is one of the most popular programming language and is supported by large corporations such as Google, Miscrosoft. So, learning JS you are ensured that your skill is transferable and is needed in current job trends beside use it to write plug in for your games.
2/ Let start with core features of JS in comparision with other OOp.
a. JS does not support class-based structure. What this mean is you don't create object by declaring class.
b. JS is weak type language (If your background is JAVA you would be familiar with type when declaring variables, properties and methods), but does not mean JS absent type.
There are 5 primitive types and reference type. reference type is actually object (If you're Ruby background, this is confusing because Ruby everything is object).
Example: 5 primitive types.
String : var playerName = "Ralph";Boolean : var eventSwitch = true;Number : var playerHP = 34;Null : var playerSprite = null;Undefined : var playerMP; // when define variable with no value, undefined will automatically assign.Example: reference type
var sprite = new Object();The different between primitive type and reference type is primitive type stores data while reference type (object) stores reference of object (pointer to memory location).
c. In JS null and undefined have no methods while string, number and boolean have methods. This possible because behind the scene what JS does is simply convert these primitive types to wrapper types (wrapper type is object) which allows you to invoke the methods on string, number and boolean. You can manually create wrapper type but it is best to avoid creating them because JS automatically create it for you.
Example: wrapper type corresponding to primitive type.
var eventSwitchBoolean = false; // primitive type of boolean evaluates to falsevar eventSwitchObject = new Boolean(false); // wrapper type evaluates as objectvar playerLevel = 10; // evaluates as primitive type numbervar playerLevelObject = new Number(10); // evaluates as objectd. There are two ways to create an object in JS. Either use new operator or object literal syntax {}
Example: The example below create an object with new operator and create object with literal syntax.
var player1 = new Object(); // create object with new operator var player2 = {}; // create object with literal syntaxContinue August 8th.
e. JS object is extensible. What this means is you can add or remove properties at any time. This is not possible in some other OOP language.
Example: Adding and deleting properties after object created.
var player1 = { name: "Ralph"};player1.age = 18; // adding age property to player1 object.player1.level = 1; // adding level property to player1 object.delete player.name; // use keyword delete to delete object property.Now you can see how flexible JS object is. In OOP such as Java, to create object you must define class first and once object created you can't add or delete object's properties like you can do in JS. However, JS also has methods to prevent any modification to object.
Exmaple: JS has a few methods to prevent modifying object and these methods work slightly different.
var player1 = { name: "Ralph"};Object.preventExtensions(player1); // now you can't add any more properties to object but you can delete properties and change their types.Object.seal(player1); // not only you can't add more properties you can't remove properties but you can read and write to properties' values.Object.freeze(player1); // you can only read object properties.f. JS has this object. Now it sounds confusing. this is an object and it is in every scope. this object reference to the object invoke it. Similar to self keyword in Ruby and this in Java. You will see this object uses a lot, especially in manipulating DOM (DOM is html tree structure).
Example 1:
var player1 = { name: "Ralph", say: function() { alert(this.name); } // this.name is equivalent to player1.name};Example 2:
var name = "someone";function myName() {alert(this.name);}var player1 = { name: "Ralph", say: myName};var player2 = { name: "Elin", say: myName};player1.say(); // Ralphplayer2.say(); // ElinmyName(); // someoneSo, the this refers to the scope of the object invokes it. In above example when myName() method is invoked, the this refer to global object, therefore the out put is "someone". There's actually a trick to bind this to specific object by assign this to a variable. In addition there are other methods to manipulate this. I will talk about these methods later because they are properties of function object. These methods are; call(), apply() and bind()
August 16th
g. There are two different types of properties in JS. As you seen above properties are in the form of name and value pair and these properties are data properties. The other type of properties are accessor properties ( they equivalent to setter and getter in Ruby and Java.)
Example: accessor properties
var player1 = { _name: "Ralph", // by convention when define accessor property, underscore is placed before property name.get name() { return this._name; }, // read property _nameset name(value) { this._name = value; } // write property _name};So the different between data properties and accessor properties is data properties has data as values while accessor properties contain methods to read and properties values.
h. In JS properties have descriptors (attributes). Ok this is somewhat confusing when your first OOP is not JS, you would thought of properties in JS are similar to that of fields or variables in JS or Ruby. In Java for example, when you want to declare enum type. You would do something like this.
public enum JavaEnum {
ONE(1),
TWO(2);
}
Not cool and verbose. In JS, you can switch properties into enum or not enum by just changing properties descriptors. By default when you created properties are enumerable.
Example: Change propertys enum to false by set property descriptor enumerable to false.
var player1 = {}; // create object player1player1.name = "Ralph"; // add property name// use Object.defineProperty() method to change properties descriptors.Object.defineProperty(player1, "name", { enumerable: false }); Data properties and accessor properties have different set of descriptors.
Example: The example below you can use Object.defineProperty() method to add and config property descriptors to the object player1 at once.
//create object player1var player1 = {}; // add data property name and config property descriptorsObject.defineProperty(player1, "name", {value: "Ralph",enumerable: true,configurable: true,writable: true});// create object and propertyvar player1 = {_name: "Ralph"};// add and config accessor properties descriptorsObject.defineProperty(player1, "name", {enumerable: true,configurable: true,get: function() {return this._name;},set: function(value) {this._name = value;}});
As you can see data properties and accessor properties share enumerable and configurable descriptors. While data properties have descriptors that accessor properties do not have such as writable and value descriptors.
Agust 17th
i. Ok now you know JS has objects and two types properties (data and accessor) and each type property has set of descriptors. Up to this point, the properties you know of are objects' own properties. What this means is those properties are belong to that object and not sharing to any other objects, its instances.
When object created a hidden prototype property created automatically for that object. Prototype property itself is an object therefore it has properties of its own. Prototype properties share with instances of the object.
Example: Prototype property
var player1 = new Object();alert(player1.toString()); // output [object Object]In the example above I did not add any property to the player1 object but I was able to call toString() property. The explanation for this, is player1 object inherits method property toString() from the Object.prototype. The Object.prototype has some of method properties; toString(), valueOf(), hasOwnProperty, propertyIsEnumerable(), isPrototypeOf(). This means these properties sharing with instances of Objects. As I mentioned, when an object is created the prototype property also created but you just can't see it and this prototype property has value point to the object created it.
Example. Check prototype property value
var player1 = {};var prototype = Object.getPrototypeOf(player1);alert(prototype); // output [object Object]
j. In JS, function is an object. When I learnt JS I thought function was a method that can define outside of object. I was wrong, function is an object.
Example: Create function with literal syntax and new keyword (best practice do not create function with new keyword)
//Create function with literal syntaxfunction sayName(newName) {return this.name = newName;} var playerName = sayName("Ralph");alert(playerName);//Create function with new keywordvar sayName = new Function("newName", "return newName");var playerName = sayName("Ralph");alert(playerName);There are two ways to create functions with syntax literal and each works differently.
Example: Create Declaration and Expression
//Create declaration functionfunction sayName(newName) {return this.name = newName;}//Create expression functionvar myName = function(newName) {return this.name = newName;};The different when create declaration function and expression is function declaration has a name after function keyword while function expression has no name, expression function also called anonymous function. Both functions work different.
Example: Declaration vs Expression
var playerName = sayName("Ralph"); // output Ralph//Create declaration functionfunction sayName(newName) {return this.name = newName;}var playerName2 = myName("Ralph"); // you get error//Create expression functionvar myName = function(newName) {return this.name = newName;};The different is obvious. You can call declaration function before it is created this possible because JS hoisted this function while that is not possible with expression function.
Function can be used as value and argument of another function
Example: Function as value and argument of another function
//Function as valuefunction sayName(newName) {return this.name = newName;}var myName = sayName;//Function as argument of another functionvar numbers = [ 1, 5, 8, 4, 7, 10, 2, 6 ];numbers.sort(function(first, second) {return first - second;});Function created inside of object is called method. If you are Ruby you would familiar with def keyword to create methods inside object. In JS, create method is same as create function name value pair where value is function.
Example: Function as method
var player { sayName : function() { alert("Ralph"); }};player.sayName(); // output RalphJS does not support overloading. What this means is if you have two functions of the same name, the later will evaluate.
Example: later function override previous function
function sayName(name) {alert(name);}function sayName() {alert("my name is not Ralph");}sayName("Ralph"); // my name is not RalphIn JS, you can pass as many as parameters to functions without having to declare them in first place.
Example: Passing parameters to function.
function sum() {var result = 0,i = 0,len = arguments.length;while (i < len) {result += arguments;i++; }return result;}alert(sum(1, 2)); // 3alert(sum(3, 4, 5, 6)); // 18alert(sum(50)); // 50alert(sum()); // 0k. Create custom objects in JS. As you know JS does not support class-based, so what you been doing so far was create instance of Objects (one of built-in objects in JS). Create objects in JS is rather simple similar to create function, the only different is the name is capitalized.
Example: Create custom objects
//Create object constructor, similar to create function except for the name is capitalized.function Player() {this.sayName = "My Name Is Ralph";}//Create object Player with new keywordvar ralph = new Player();alert(ralph.sayName);I stop here. There's really good book which I recommend.
The Principles of Object-Oriented JavaScript http://www.amazon.com/Principles-Object-Oriented-JavaScript-Nicholas-Zakas/dp/1593275404
1/ Why is Javascript?
a. Javascript (JS) is one of the most popular programming language and is supported by large corporations such as Google, Miscrosoft. So, learning JS you are ensured that your skill is transferable and is needed in current job trends beside use it to write plug in for your games.
2/ Let start with core features of JS in comparision with other OOp.
a. JS does not support class-based structure. What this mean is you don't create object by declaring class.
b. JS is weak type language (If your background is JAVA you would be familiar with type when declaring variables, properties and methods), but does not mean JS absent type.
There are 5 primitive types and reference type. reference type is actually object (If you're Ruby background, this is confusing because Ruby everything is object).
Example: 5 primitive types.
String : var playerName = "Ralph";Boolean : var eventSwitch = true;Number : var playerHP = 34;Null : var playerSprite = null;Undefined : var playerMP; // when define variable with no value, undefined will automatically assign.Example: reference type
var sprite = new Object();The different between primitive type and reference type is primitive type stores data while reference type (object) stores reference of object (pointer to memory location).
c. In JS null and undefined have no methods while string, number and boolean have methods. This possible because behind the scene what JS does is simply convert these primitive types to wrapper types (wrapper type is object) which allows you to invoke the methods on string, number and boolean. You can manually create wrapper type but it is best to avoid creating them because JS automatically create it for you.
Example: wrapper type corresponding to primitive type.
var eventSwitchBoolean = false; // primitive type of boolean evaluates to falsevar eventSwitchObject = new Boolean(false); // wrapper type evaluates as objectvar playerLevel = 10; // evaluates as primitive type numbervar playerLevelObject = new Number(10); // evaluates as objectd. There are two ways to create an object in JS. Either use new operator or object literal syntax {}
Example: The example below create an object with new operator and create object with literal syntax.
var player1 = new Object(); // create object with new operator var player2 = {}; // create object with literal syntaxContinue August 8th.
e. JS object is extensible. What this means is you can add or remove properties at any time. This is not possible in some other OOP language.
Example: Adding and deleting properties after object created.
var player1 = { name: "Ralph"};player1.age = 18; // adding age property to player1 object.player1.level = 1; // adding level property to player1 object.delete player.name; // use keyword delete to delete object property.Now you can see how flexible JS object is. In OOP such as Java, to create object you must define class first and once object created you can't add or delete object's properties like you can do in JS. However, JS also has methods to prevent any modification to object.
Exmaple: JS has a few methods to prevent modifying object and these methods work slightly different.
var player1 = { name: "Ralph"};Object.preventExtensions(player1); // now you can't add any more properties to object but you can delete properties and change their types.Object.seal(player1); // not only you can't add more properties you can't remove properties but you can read and write to properties' values.Object.freeze(player1); // you can only read object properties.f. JS has this object. Now it sounds confusing. this is an object and it is in every scope. this object reference to the object invoke it. Similar to self keyword in Ruby and this in Java. You will see this object uses a lot, especially in manipulating DOM (DOM is html tree structure).
Example 1:
var player1 = { name: "Ralph", say: function() { alert(this.name); } // this.name is equivalent to player1.name};Example 2:
var name = "someone";function myName() {alert(this.name);}var player1 = { name: "Ralph", say: myName};var player2 = { name: "Elin", say: myName};player1.say(); // Ralphplayer2.say(); // ElinmyName(); // someoneSo, the this refers to the scope of the object invokes it. In above example when myName() method is invoked, the this refer to global object, therefore the out put is "someone". There's actually a trick to bind this to specific object by assign this to a variable. In addition there are other methods to manipulate this. I will talk about these methods later because they are properties of function object. These methods are; call(), apply() and bind()
August 16th
g. There are two different types of properties in JS. As you seen above properties are in the form of name and value pair and these properties are data properties. The other type of properties are accessor properties ( they equivalent to setter and getter in Ruby and Java.)
Example: accessor properties
var player1 = { _name: "Ralph", // by convention when define accessor property, underscore is placed before property name.get name() { return this._name; }, // read property _nameset name(value) { this._name = value; } // write property _name};So the different between data properties and accessor properties is data properties has data as values while accessor properties contain methods to read and properties values.
h. In JS properties have descriptors (attributes). Ok this is somewhat confusing when your first OOP is not JS, you would thought of properties in JS are similar to that of fields or variables in JS or Ruby. In Java for example, when you want to declare enum type. You would do something like this.
public enum JavaEnum {
ONE(1),
TWO(2);
}
Not cool and verbose. In JS, you can switch properties into enum or not enum by just changing properties descriptors. By default when you created properties are enumerable.
Example: Change propertys enum to false by set property descriptor enumerable to false.
var player1 = {}; // create object player1player1.name = "Ralph"; // add property name// use Object.defineProperty() method to change properties descriptors.Object.defineProperty(player1, "name", { enumerable: false }); Data properties and accessor properties have different set of descriptors.
Example: The example below you can use Object.defineProperty() method to add and config property descriptors to the object player1 at once.
//create object player1var player1 = {}; // add data property name and config property descriptorsObject.defineProperty(player1, "name", {value: "Ralph",enumerable: true,configurable: true,writable: true});// create object and propertyvar player1 = {_name: "Ralph"};// add and config accessor properties descriptorsObject.defineProperty(player1, "name", {enumerable: true,configurable: true,get: function() {return this._name;},set: function(value) {this._name = value;}});
As you can see data properties and accessor properties share enumerable and configurable descriptors. While data properties have descriptors that accessor properties do not have such as writable and value descriptors.
Agust 17th
i. Ok now you know JS has objects and two types properties (data and accessor) and each type property has set of descriptors. Up to this point, the properties you know of are objects' own properties. What this means is those properties are belong to that object and not sharing to any other objects, its instances.
When object created a hidden prototype property created automatically for that object. Prototype property itself is an object therefore it has properties of its own. Prototype properties share with instances of the object.
Example: Prototype property
var player1 = new Object();alert(player1.toString()); // output [object Object]In the example above I did not add any property to the player1 object but I was able to call toString() property. The explanation for this, is player1 object inherits method property toString() from the Object.prototype. The Object.prototype has some of method properties; toString(), valueOf(), hasOwnProperty, propertyIsEnumerable(), isPrototypeOf(). This means these properties sharing with instances of Objects. As I mentioned, when an object is created the prototype property also created but you just can't see it and this prototype property has value point to the object created it.
Example. Check prototype property value
var player1 = {};var prototype = Object.getPrototypeOf(player1);alert(prototype); // output [object Object]
j. In JS, function is an object. When I learnt JS I thought function was a method that can define outside of object. I was wrong, function is an object.
Example: Create function with literal syntax and new keyword (best practice do not create function with new keyword)
//Create function with literal syntaxfunction sayName(newName) {return this.name = newName;} var playerName = sayName("Ralph");alert(playerName);//Create function with new keywordvar sayName = new Function("newName", "return newName");var playerName = sayName("Ralph");alert(playerName);There are two ways to create functions with syntax literal and each works differently.
Example: Create Declaration and Expression
//Create declaration functionfunction sayName(newName) {return this.name = newName;}//Create expression functionvar myName = function(newName) {return this.name = newName;};The different when create declaration function and expression is function declaration has a name after function keyword while function expression has no name, expression function also called anonymous function. Both functions work different.
Example: Declaration vs Expression
var playerName = sayName("Ralph"); // output Ralph//Create declaration functionfunction sayName(newName) {return this.name = newName;}var playerName2 = myName("Ralph"); // you get error//Create expression functionvar myName = function(newName) {return this.name = newName;};The different is obvious. You can call declaration function before it is created this possible because JS hoisted this function while that is not possible with expression function.
Function can be used as value and argument of another function
Example: Function as value and argument of another function
//Function as valuefunction sayName(newName) {return this.name = newName;}var myName = sayName;//Function as argument of another functionvar numbers = [ 1, 5, 8, 4, 7, 10, 2, 6 ];numbers.sort(function(first, second) {return first - second;});Function created inside of object is called method. If you are Ruby you would familiar with def keyword to create methods inside object. In JS, create method is same as create function name value pair where value is function.
Example: Function as method
var player { sayName : function() { alert("Ralph"); }};player.sayName(); // output RalphJS does not support overloading. What this means is if you have two functions of the same name, the later will evaluate.
Example: later function override previous function
function sayName(name) {alert(name);}function sayName() {alert("my name is not Ralph");}sayName("Ralph"); // my name is not RalphIn JS, you can pass as many as parameters to functions without having to declare them in first place.
Example: Passing parameters to function.
function sum() {var result = 0,i = 0,len = arguments.length;while (i < len) {result += arguments;i++; }return result;}alert(sum(1, 2)); // 3alert(sum(3, 4, 5, 6)); // 18alert(sum(50)); // 50alert(sum()); // 0k. Create custom objects in JS. As you know JS does not support class-based, so what you been doing so far was create instance of Objects (one of built-in objects in JS). Create objects in JS is rather simple similar to create function, the only different is the name is capitalized.
Example: Create custom objects
//Create object constructor, similar to create function except for the name is capitalized.function Player() {this.sayName = "My Name Is Ralph";}//Create object Player with new keywordvar ralph = new Player();alert(ralph.sayName);I stop here. There's really good book which I recommend.
The Principles of Object-Oriented JavaScript http://www.amazon.com/Principles-Object-Oriented-JavaScript-Nicholas-Zakas/dp/1593275404