Home > HowTo, Javascript > Javascript CREATING OBJECTS AND METHODS


1)Scope and Hoisting
Scope = a variable visibility
– globoal scope, out of a function
– function scope, inside a function
Does not support block scope (inside if/else for example)
Hoisting : When a var is declared in a block it is elevated to function scope

2)Mangaging the Global Namespace
Global names variables can be a serious trouble.
Namespace is used to avoid name clashes they are:
-Immediately invoked functions
-Strict mode

A) Immediate invoked function, wrap in anonymous function call.

(function() {
//variables defined here will disappear after it ends
//same happen with invoed functions within
var localVar = .. ;
	function localFunc() {
		localVar = 99;  //uses the previously variable that can be used within last function
	localFunc() ; // Run it
}) ();
Open and close () is an operator call, prompting function execution, so () (); executes the function immediatly.
function x() {}
a = x;
a(); // =>

B) Namespaces
Another way to avoid global name clashes.
Namespace is a global var with vars and funcs attched to it.
2 func and 2 vars

var MyNamespace = {
	myFunc1: function(somePara) {
	myFunc2: function(somePara) {
	message: "Hello World",
	count: 53
MyNamespace.message = "Good bye";

Namespaces do not provide any privacy or enacapsulation, are all global vars.
NOTE: use namespace WORD is a way to control

C) Strict Mode
If you omit var keyword var becomes global!

function fun() {
	var code = 1;
	count = 10;    // GLOBAL
	"use strict";  //will not become global


var radius = 100 * Math.random();
var area = Math.PI * Math.pow(radius, 2);
JSON convert value 
var anObj
var anObjAsJSONString = JSON.stringify(anObj)
var anObjAgain = JSON.parse(anObjAsJSONString);


var age = parseInt(ageEnteredByUser);
var height = parseFloat(hByUser);
if (isNan(age) || isNan(height))
	alert("Invalid input);

The isNaN() function determines whether a value is an illegal number (Not-a-Number).
This function returns true if the value is NaN, and false if not

JSON .parse     - (receive the json)
JSON .stringfy  - (send object data)

var employee1 = new Object();
var employee2 = {};

Creating objects properties and methods 
employee1.name = "John Smith";
employe1.salary = 1000;
employee1.payRise = function(amount) {
//inside a method, 'this' means the current object (go up the code until the object)
	this.salary += amount;
	return this.salary;
var newSalary = employee1.payRise(500);
document.write("New salary " + newSalary);

NOTE: JS does not support function overloading, it will overwrite the last one.
No need to create a class, create directly an object.

Using Object Literal Notation (More clear)

var employee2 = {
	name: "Mary Jones",
	salary: 2000,
	payRise: function(amount) {
		this.salary += amount;
		return this.salary;
	displayDetails: function() {
		alert(this.name + " is " + this.age + " and earns " + this.salary);

Create functions are used to easily create new objects with the specified properties.
variable that receives a function is a method, to be called ‘this’

var Account = function (id, name) {
	this.id = id;
	this.name = name;
	this.balance = 0;
	this.numTrans = 0;
var acc1 = new Account(1, "John");
var acc2 = new Account(2, "Mary");
acc1.constructor both reference to Account construct function.

After you have defined a constructor function, you can use the constructor to create a new object by
using the new keyword. You can pass parameters into the constructor function to specify the initial values
for the object. When you create an object by using the new keyword, JavaScript performs the following
1. creates new obj
2. set constructor property to reference to a constructor function
3. Assigns ‘this’ to refer to the new obj
4. invokes code to set properties on the obj

Using Prototypes
With the constructor there is a waste of resources because each code is a copy of the same.

Prototype is an object which u can assign new properties and methods, use it as a blueprint.

Account.protoype = {
	deposit: function(amount) {
		this.balance += amount;
	displayDetails: function() [
		alert(this.id + ", " + this.name + " balance $" + this.balance);

var acc1 = new Account(1, "john");

This Object provides functionality such as the toString method.

Using the Object.create Method

var Account = function(id, name) { .. };
Account.prototype = { .. };
acc1 = new Account(...);
//create na obj by using the Account prototype
var obj2 = Object.create(Object.getPropertyOf(acc1));

acc1 object was created by using the Account constructor

In JS everything is an object. Is is possible to implement object-oriented feature such as
inheritance and encapsulation.
A) Implementing Encapsulation
It shields external code from the internal workgins of a class.
Javascript does not have public/protected/private to specify access.
But it uses a technice known as CLOSURES to achieve encapsulations.

var person - function(name, age)
	//priavete, inside a func
	var _name,_age;
	//public access funcs
	this.getName = function() 
		return _name; 	

The general syntax for the Object.create() method is as follows:
Object.create(prototypeObject, propertiesObject)

The prototypeObject parameter specifies the object to use as the prototype for the new object.
You can invoke the Object.getPrototypeOf() method if you want to obtain the prototype of an existing object to use here.
The propertiesObject parameter is optional, and specifies an object whose properties will be added
into the new object. This object takes the form of a collection of property descriptors. A property
descriptor specifies the value stored in the property, and can also specify other attributes such as
whether the property is read-only or can be updated; properties are read-only unless you set the
writable attribute to true.
The following example creates an object by using a null prototype, and adds two simple properties:

var obj1 = Object.create(null, {
prop1: {value: "hello", writable: true}, // read/write property
prop2: {value: "world" } // read-only property

You implement inheritance by defining an object that extends an existing object.
Object.create function to implement
1. Define at base constructor and prototype
2. Define the derived constructor
3. Set the prototype property of the dervied constructor to be an instance of the base object.
4. Reset the constructor property in the dervied prototype so that it refers back to the dereived constructor.

Adding Func to Existing Object

var Account = function (id, name) { ... };
// Account prototype, same as before.
Account.prototype = { ... };
acc1 = new Account(...);
// Create an object by using the Account prototype.
var obj2 = Object.create(Object.getPrototypeOf(acc1

The acc1 object was created by using the Account constructor function which references the prototype
that contains the deposit, withdraw, and displayDetails methods

more refined control over the inheritance mechanism is to make use of constructor function prototypes, as follows:
1. Define the base constructor and prototype.
2. Define the derived constructor.
3. Set the prototype property of the derived constructor to be an instance of the base object. This
ensures that the derived object has access to all the members defined in the base prototype.
4. Reset the constructor property in the derived prototype so that it refers back to the derived

// Base constructor.
var Person = function(name, age) {
this.name = name;
this.age = age;
// Base prototype.
Person.prototype = {
haveBirthday: function() {
// Derived constructor.
var Student = function(name, age, subject) {
this.name = name;
this.age = age;
this.subject = subject;
// Set the derived prototype to be the same object as the base prototype,
// and reset that derived prototype so that it uses the correct constructor.
Student.prototype = new Person();
Student.prototype.constructor = Student;
// Create a derived object and invoke any methods defined in the object or one of its
// parents. JavaScript uses prototype chaining to locate methods up the inheritance tree.
var aStudent = new Student("Jim", 20, "Physics");
aStudent.subject = "BioChemistry";

To extend the functionality of an object, follow
these steps:
1) Get the prototype for an object.
2) Assign a new property to the object, to represent the new feature that you want to add.

var Point = function(x,y){
	this.x = x,
	this.y = y,
Point.prototype.moveBy = function(deltaX, deltaY) {
	this.x += deltaX;
	this.y += deltaY;
Point.prototype.moveTo = function(otherPoint) {
	this.x = otherPoint.x;
	this.y = otherPoint.y;

var p1= new Point(100, 200);
p1.moveBy(10, 20);
var p2= new Point(25, 50);
alert("p2.x: " + p2.x + " p2.y: " + p2.y);

The following example shows how to add functionality to an existing object. The code defines a
constructor function named Point, to represent a coordinate point that has x and y properties. The code
then adds methods named moveBy() and moveTo() to the prototype object for Point, and shows how
these methods are available on all Point objects.


function SetColor(color) {
	this.color = color;
SetColor.apply(p1, ["red"]);
alert(p1.color); // Displays "red"

The Point object, p1, is passed as the this parameter, and the parameter list containing the single string
“red” is passed as the color parameter to the SetColor method. The result is that the color property of p1
is set to “red”.
(updated Jul. 2014)

Categories: HowTo, Javascript Tags: , ,
  1. No comments yet.
  1. August 9th, 2017 at 01:17 | #1
  2. August 12th, 2017 at 19:16 | #2
  3. August 13th, 2017 at 07:16 | #3
  4. August 13th, 2017 at 23:47 | #4
  5. August 14th, 2017 at 15:02 | #5
  6. August 14th, 2017 at 23:08 | #6
  7. August 15th, 2017 at 07:14 | #7
  8. August 15th, 2017 at 12:31 | #8
  9. August 15th, 2017 at 18:38 | #9
  10. August 18th, 2017 at 09:17 | #10