Monthly Archives: September 2017

f.prototype and constructor (js)


In modern JavaScript we can set a prototype using __proto__.

But in the old times, there was another (and the only) way to set it: to use a “prototype” property of the constructor function.

It is known that, when “new F()” creates a new object…

the new object’s [[Prototype]] is set to F.prototype

In other words, if function F has a prototype property with a value of the object type, then the “new” operator uses it to set [[Prototype]] for the new object.

Setting Rabbit.prototype = animal literally states the following: “When a new Rabbit is created, assign its [[Prototype]] to animal”.

Constructor Property

As stated previous, we have the “prototype” property point to whatever object we want as the parent class to be inherited from future “new”-ed functions.

However, what is this “prototype” property before our assignment?
Every function has the “prototype” property even if we don’t supply it.

The default “prototype” property points to an object with the only property constructor that points back to the function itself.

You can check it like this:

Rabbit prototype by default

By default whatever objects created from “new Rabbit()” will inherit from Rabbit.
The instance ‘rabbit’ has constructor property which points to Rabbit.

We can use constructor property to create a new object using the same constructor as the existing one.

Like here:

Future manipulations of the prototype property

JavaScript itself does not ensure the right “constructor” value.

Yes, it exists in the default object that property prototype references, but that’s all. What happens with it later – is totally on us.

In this example, we see that we repointed the prototype to a totally different object. Thus, other instances of Rabbit, will be deriving from the object with property jumps: true.

The assumption that instances of Rabbit will have a ‘Rabbit’ constructor will then be false.

So, to keep the right “constructor” we can choose to add/remove properties to the default “prototype” instead of overwriting it as a whole:

Or you can reconstruct it yourself. Just make sure to include the constructor property and set it to your this object:

The only thing F.prototype does: it sets [[Prototype]] of new objects when “new F()” is called.

The value of F.prototype should be either an object or null: other values won’t work.

The “prototype” property only has such a special effect when is set to a constructor function, and invoked with new.

By default all functions have F.prototype = { constructor: F }, so we can get the constructor of an object by accessing its “constructor” property.


The assignment to Rabbit.prototype sets up [[Prototype]] for new objects. The new object ‘rabbit’ then points to Rabbit. The instance rabbit’s [[Prototype]] then is pointing to Rabbit’s default prototype object with its constructor property.

Then Rabbit’s prototype points to an empty object. However, rabbit’s [[Prototype]] already is referencing Rabbit’s default prototype object with its constructor property. Hence that’s why rabbit.eats is true.

Problem 1

solution: true


Problem 2

Solution: false


Problem 3


All delete operations are applied directly to the object. Here delete rabbit.eats tries to remove eats property from rabbit, but it doesn’t have it. So the operation won’t have any effect.


Problem 4


Constructors (js)

The purpose of constructors is to implement reusable object creation code

Constructor functions technically are regular functions. There are two conventions though:

They are named with capital letter first.
They should be executed only with “new” operator.

Every function is an object, and when an object is created with “new”, it runs through the constructor.
1) The constructor then uses ‘this’ and assigns an empty object to it.
2) It will then add properties you specify onto “this”.
3) Finally, it returns this.

Constructors in Javascript is used to construct objects and can be called many times by any references.

However, constructors can also be created and called just once, and not be saved for later use.


ref –

Inside a function, we can check whether it was called with new or without it, using a special property.
This can be used to allow both new and regular syntax to work the same. The reason why we care about “new” is because when we “new” a function, it creates an object out of it with its own “this”.

However, if we do not use “new”, the value of this becomes the global object.
In a web browser the global object is the browser window.

For example:

The reason why logs Cody Lindley is because the ‘this’ inside the function references the window global object. Hence when we attach the attribute name to this, it attaches name to the window object. the ‘this’ has nothing to do with the object Person.

Now, when we use new Object, we create an object on the heap, and “this” in our function refers to that object. IT IS NOT connected to the (global or window) object.

Hence, when we log, it works because cody is that object in the heap. The this in the function, refers to cody.

In order to make sure the “new” is always applied so that we get some consistency, we can check for to see if “new” was used to create the object. If not, then we need to force it by returning an object using new.

Return from Constructors

Usually, constructors do not have a return statement. Their task is to write all necessary stuff into this, and it automatically becomes the result.
But if there is a return statement, then the rule is simple:
If return is called with object, then it is returned instead of this.
If return is called with a primitive, it’s ignored.
In other words, return with an object returns that object, in all other cases this is returned.

Methods in Constructor

Having a method in a constructor means you add the method definition as a property to “this”. Once that happens,
after you construct an object, you are free to call that method.

Is it possible to create functions A and B such as new A()==new B()?

Yes, it’s possible.

If a function returns an object, then new returns it instead of this.

So thay can, for instance, return the same externally defined object obj:

null vs undefined (js)

The difference between null and undefined is as follows:


undefined: used by JavaScript and means “no value”.

– Uninitialized variables
– missing parameters
– unknown variables have that value.

> var noValueYet;
> console.log(noValueYet);

> function foo(x) { console.log(x) }
> foo()

> var obj = {};
> console.log(obj.unknownProperty)


null: used by programmers to indicate “no value”, e.g. as a parameter to a function.
Examining a variable:

console.log(typeof unknownVariable === “undefined”); // true

var foo;
console.log(typeof foo === “undefined”); // true
console.log(foo === undefined); // true

var bar = null;
console.log(bar === null); // true

Stack and Heap

The stack is the memory set aside as scratch space for a thread of execution.

When a function is called, a block is reserved on the top of the stack for local variables, parameters, and some bookkeeping data.

When that function returns (finishes execution), the block becomes unused (all the variables gets popped) and can be used the next time a function is called.

The stack is always reserved in a LIFO (last in first out) order; the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack; freeing a block from the stack is nothing more than adjusting one pointer.

The heap is memory set aside for dynamic allocation. Unlike the stack, there’s no enforced pattern to the allocation and deallocation of blocks from the heap; you can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time; there are many custom heap allocators available to tune heap performance for different usage patterns.

Each thread gets a stack, while there’s typically only one heap for the application (although it isn’t uncommon to have multiple heaps for different types of allocation).

The stack is attached to a thread, so when the thread exits the stack is reclaimed. The heap is typically allocated at application startup by the runtime, and is reclaimed when the application (technically process) exits.

The size of the stack is set when a thread is created. The size of the heap is set on application startup, but can grow as space is needed (the allocator requests more memory from the operating system).

The stack is faster because the access pattern makes it trivial to allocate and deallocate memory from it (a pointer/integer is simply incremented or decremented), while the heap has much more complex bookkeeping involved in an allocation or deallocation. Also, each byte in the stack tends to be reused very frequently which means it tends to be mapped to the processor’s cache, making it very fast.

Another performance hit for the heap is that the heap, being mostly a global resource, typically has to be multi-threading safe, i.e. each allocation and deallocation needs to be – typically – synchronized with “all” other heap accesses in the program.

Javascript memory allocation

When you call a function, amongst other things a variable environment for that call is created, which has something called a “variable object”.

The “variable object” has properties for the
– arguments to the function
– all local variables declared in the function
– and all functions declared within the function (along with a couple of other things)

When a closure survives the function returning (which can happen for several reasons), the variable object for that function call is retained in memory (heap) by the reference from the closure.

At first glance, that would suggest that the stack isn’t used for local variables; in fact, modern JavaScript engines are quite smart, and may (if it’s worthwhile) use the stack for locals that aren’t actually used by the closure. (Naturally, the stack is still used for keeping track of return addresses and such.)

Due to our function bar (which is a closure) uses and references c, if our function call ends and pops, our closure bar is still chained to “foo”, and thus be able to use c. Depending on the js engine, it may then move “c”

Javascript pass by reference or pass by value

Javascript parameters are pass by value, the value is that of the reference address.

obj1 is a reference that points to the object. Specifically, it points to the address of the object.
In the function changeStuff, its parameter ‘numParam’ is pushed as a reference on to the local function stack. It then copies by value the address of the object pointed to by obj1.

Parameter reference dereferences the object

Inside changeStuff, when we access the property item, our reference would dereference the object and get the value of item. Then assign it a new value “changed”. That’s why when the function finishes and pops, our obj1 reference outside will see that its property item was dereferenced and changed to “changed”.


Simply points away

The other situation is that we assign our parameter reference to another object. When this happens, we point our reference away from the object that obj1 points to, and onto the new object. That’s why when our function exits, the obj1 still points to its own object and the item property is still “unchanged”

Primitives – Pass by Value

In JavaScript there are 5 primitive types: undefined , null , boolean , string and number. They are all passed by value.

Typing in javascript

strong/weak can be thought of in relation to how the compiler, if applicable, handles typing.

Weakly typed means the compiler, if applicable, doesn’t enforce correct typing. Without implicit compiler interjection, the instruction will error during run-time.

“12345” * 1 === 12345 // string * number => number

Strongly typed means there is a compiler, and it wants you an explicit cast from string to integer.

(int) “12345” * 1 === 12345

In either case, some compiler’s features can implicitly alter the instruction during compile-time to do conversions for you, if it can determine that is the right thing to do.

Thus far, JavaScript can be categorized as Not-Strongly-Typed. That either means it’s weakly-typed or un-typed.

Arrow function (e6 js)

For arrow functions, this is picked up from surroundings (lexical).

In other words, Arrow functions are lexically scoped; this means that

their ‘this’ is bound to the context of the surrounding scope

That is to say, whatever ‘this’ refers to can be preserved by using an arrow function.


Test2() Constructor: Jabba the Hut
Age is: 36
Ryu.. yells out tats makesen bukakyu
Jabba the Hut yells out shoooo ryu ken!

Closures (inner functions)

A closure is the local variables for a function – kept alive after the function has returned

In other words,

a closure is formed when an inner functions is made accessible outside of the function in which it was contained, so that it may be executed after the outer function has returned.

At which point it still has access to the local variables, parameters and inner function declarations of its outer function.

Those local variables, parameter and function declarations (initially) have the values that they had when the outer function returned and may be interacted with by the inner function.

1) We get the reference of the returned inner function.
2) Pass in a parameter so its inner function can grab onto it.
3) Execute the reference, which creates scope and grabs.

Boooom! param is: 88

Now we do the same thing, but in a loop.

Boooom! param is: 0
Boooom! param is: 1
Boooom! param is: 2

In an async situation, let’s say we have setTimeout that asks for a function to execute when a certain number of seconds have passed.

If we pass a function with a parameter (like what we have above), we’ll be able to have a closure and save state as well. We pass in one variable to the parameter, and the closure references that 1 parameter.

But because we do this in a callback, we must combine the 3 steps together.


1) We get the reference of the returned inner function.
2) Pass in a parameter so its inner function can grab onto it.
3) Execute the reference, which creates scope and grabs.

becomes an Immediately Invoked Function Expression:


First it logs the callback function because we immediately execute it:
‘setTimeout: 88 √’

Then it returns the inner function. Due to the execution of the callback function, the inner function will create scope and reference parameter index from its local.

After 2 seconds!…..inner func logs: 88

Async situation, in a loop:

We run an async operation where it executes a function after a second.
The inner function references it parameter, which is passed in via an Immediately Invoked Function Expression.

Under the hood, a closure is a stack-frame (which contains accessible variables), which has not been deallocated when the function returns. (as if a ‘stack-frame’ were malloc’ed instead of being on the stack!)

Closures are frequently used in JavaScript for object data privacy, in event handlers and callback functions, and in partial applications, currying, and other functional programming patterns.

What is a Closure?

A closure is the combination of a function enclosed with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

First, a simple Object with public and private properties

output: – BladeMaster

Adding public function, and a Closure

To declare a closure, simply define a function inside another function. This is also called an inner function. Inner functions, are private scope by default. You can make it public for instances by assign public properties to it. In other words, you expose the function to be used.

If you assign a property to a function, you make it public and the instance can call it.
However, if its just the function, then it is used as private function for your class to use.


Constructing Orc: BladeMaster
This is an inner function

Using property variable in closure

After you define the closure, you can simply use the property name as is. i.e property ‘name’ in closure ‘growls’.

Using in the closure vs in the object

Closure has access to

  • its own scope
  • parent function’s scope
  • parent function’s parameters
  • DO NOT HAVE ACCESS to parent scope’s this

Constructing Orc: BladeMaster
Toro: For the burning blade!
ERROR this is undefined

Public properties assigned to Inner Functions can access “this”

Notice that when we assign public properties on Inner Functions, we can access this.
However, a standard inner function (no public properties assigned to it) will not be able to have access to the parent scope’s this.

The Masters
who’s playing in it!?
[ { name: ‘T. Woods’, age: 37 },
{ name: ‘P. Mickelson’, age: 43 } ]
1) own vars
2) outer function’s vars
outer limits
3) outer function’s parameter
merry xmas!
4) Inside closure: undefined
1) own vars
2) outer function’s vars
outer limits
3) outer function’s parameter
merry xmas!
4) Inside closure: undefined

If we do want private inner function to access parent scope

see for detailed explanation
of using 3 ways to how to use ‘this’ in inner functions:

Using parent scope variable
Using bind or call
Using arrow

More Example

First, we create the Person object. In the constructor declaration, we have a private property called pvtArray.
Any functions within our class Person can access it as a outer scope, global variable.

We have a public property called nickname. This property is accessed with this within our class Person.

However, there is a caveat.

Let’s say we declare a public function called displayInfo. It is considered a 1st layer function and can see the ‘this’ object.

Any functions within function displayInfo are considered (2nd and later) functions. These functions cannot see the ‘this’ object and any reference to this will result in undefined.

Thus, in Person, if you are to see the commented out setTimeout function, this.nickname will be undefined.

As mentioned earlier, we can use any of the 3 ways to bind ‘this’ to the correct context: fat arrow, local stack ‘self’, or bind.

Now we are going to write a Boss class. This Boss class has a public function called peekOnRandomEmployee.

We declare a new Person in that function. Then directly call displayInfo on it.

displayInfo needs a anonymous function as a parameter for its callback. We declare a anonymous function and pass it in.
The point here is that our anonymous function is a 2nd and later level function. Thus, its ‘this’ reference is undefined.

If we are to use the fat arrow function, the this is then valid.

Boss example

Notice how it references outer function variables a and p. By definition, a function’s scope extends to all variables
and parameters declared by its surrounding parents. And of course any global variables as dictated by scope rules.

full source


XML stands for eXtensible Markup Language.

XML was designed to store and transport data.

XML was designed to be both human- and machine-readable.

XML stands for eXtensible Markup Language
XML is a markup language much like HTML
XML was designed to store and transport data
XML was designed to be self-descriptive
XML is a W3C Recommendation

XML Does Not DO Anything

like this:

Its just data. And the data looks like markup similar to HTML.

XML is just information wrapped in tags.

Someone must write a piece of software to send, receive, store, or display it

XML and HTML were designed with different goals:

XML was designed to carry data – with focus on what data is
HTML was designed to display data – with focus on how data looks
XML tags are not predefined like HTML tags are – in HTML b tag means to bold whatever text is in between. But XML tags are not predefined.

The XML language has no predefined tags.

The tags in the example above (like ‘to’ and ‘from’) are not defined in any XML standard. These tags are “invented” by the author of the XML document.

HTML works with predefined tags like ‘p’, ‘h1’, ‘table’, etc.

With XML, the author must define both the tags and the document structure.

XML is Extensible
Most XML applications will work as expected even if new data is added (or removed).

Imagine an application designed to display the original version of note.xml (‘to’ ‘from’ ‘heading’ ‘data’).

Then imagine a newer version of note.xml with added ‘date’ and ‘hour’ elements, and a removed ‘heading’.

The way XML is constructed, older version of the application can still work:

It will simply the extra data.

XML Simplifies Things

It simplifies data sharing
It simplifies data transport
It simplifies platform changes
It simplifies data availability
Many computer systems contain data in incompatible formats. Exchanging data between incompatible systems (or upgraded systems) is a time-consuming task for web developers. Large amounts of data must be converted, and incompatible data is often lost.

XML stores data in plain text format. This provides a software- and hardware-independent way of storing, transporting, and sharing data.

XML also makes it easier to expand or upgrade to new operating systems, new applications, or new browsers, without losing data.

With XML, data can be available to all kinds of “reading machines” like people, computers, voice machines, news feeds, etc.

XML Separates Data from Presentation

XML does not carry any information about how to be displayed.

The same XML data can be used in many different presentation scenarios.

Because of this, with XML, there is a full separation between data and presentation.

XML is Often a Complement to HTML

In many HTML applications, XML is used to store or transport data, while HTML is used to format and display the same data.

XML Separates Data from HTML

When displaying data in HTML, you should not have to edit the HTML file when the data changes.

With XML, the data can be stored in separate XML files.

With a few lines of JavaScript code, you can read an XML file and update the data content of any HTML page.

Self-Describing Syntax

XML uses a much self-describing syntax.

A prolog defines the XML version and the character encoding:

The next line is the root element of the document:

The next line starts a ‘book’ element:

The ‘book’ elements have 4 child elements: ‘title’, ‘author’, ‘year’, ‘price’.

The next line ends the book element:

XML Documents Must Have a Root Element

XML documents must contain one root element that is the parent of all other elements:

The XML Prolog

This line is called the XML prolog:

The XML prolog is optional. If it exists, it must come first in the document.

XML Tags are Case Sensitive

XML tags are case sensitive. The tag is different from the tag .

Opening and closing tags must be written with the same case:

XML Attribute Values Must be Quoted

XML elements can have attributes in name/value pairs just like in HTML.

In XML, the attribute values must always be quoted.


Entity References

Some characters have a special meaning in XML.

If you place a character like “<" inside an XML element, it will generate an error because the parser interprets it as the start of a new element. This will generate an XML error:

What is an XML Element?

An XML element is everything from (including) the element’s start tag to (including) the element’s end tag.

An element can contain:

other elements
or a mix of the above

In the example above:

XML Elements vs. Attributes

Take a look at these examples:

In the first example gender is an attribute. In the last, gender is an element. Both examples provide the same information.

There are no rules about when to use attributes or when to use elements in XML.

BUT, Avoid XML Attributes?

Some things to consider when using attributes are:

attributes cannot contain multiple values (elements can)
attributes cannot contain tree structures (elements can)
attributes are not easily expandable (for future changes)

Don’t end up like this:

Namespace Declaration

A Namespace is declared using reserved attributes. Such an attribute name must either be xmlns or begin with xmlns: shown as below −

The Namespace starts with the keyword xmlns.
The word name is the Namespace prefix.
The URL is the Namespace identifier.

Namespace affects only a limited area in the document. An element containing the declaration and all of its descendants are in the scope of the Namespace. Following is a simple example of XML Namespace −

Here, the Namespace prefix is cont, and the Namespace identifier (URI) as This means, the element names and attribute names with the cont prefix (including the contact element), all belong to the namespace.