Object.assign

ECMAscript 6 introduced Object.assign() to achieve this natively in Javascript.

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

The Object.assign() method only copies enumerable and own properties from a source object to a target object.

So first, we create an object called AnimalClass, with properties x, y to denote coordinates of where this animal is. We then have functions move, which literally assigns integers to the x, y properties. Then, locate, which displays where this animal is on a coordinate.

We then use Object.create to create an empty object called target. The target’s prototype is this AnimalClass. This means that whatever property or function gets appended to target, its prototype is always AnimalClass. This is so that you can inherit AnimalClass’s functionalities on this object.


— target —
{}
{ x: 0, y: 0, locate: [Function: locate], move: [Function: move] }
I’m here: 0, 0

Creating a duck via Object.assign

Now that we have a target object, what we’re trying to do is to copy all the properties and functionalities of source object(s) into this target object. Hence we define a custom anonymous object where we add property “color” and function “speak”.

It returns an object, and we test the inheritance by using its own properties, and its prototype’s functionalities.


output:

— duck —
{ color: ‘black’, speak: [Function: speak] }
true
black
quack quack
I’m here: 7, 8

Functional Inheritance

ref –
http://julien.richard-foy.fr/blog/2011/10/30/functional-inheritance-vs-prototypal-inheritance/
https://medium.com/javascript-scene/3-different-kinds-of-prototypal-inheritance-es6-edition-32d777fa16c9
http://therealmofcode.com/posts/2012/11/functional-inheritance-javascript.html

https://stackoverflow.com/questions/2800964/benefits-of-prototypal-inheritance-over-classical

Functional Inheritance

The properties you attach to the returning object are class public interface. Functions and properties you define inside function, but not as a part of the returning object, are private members accessible because of closure and invisible because they were not returned.

1) In the parent function, we first create an object on the local stack.

2) We then create private properties.

3) Create public functions and properties. Can access the private properties previously created by scope.

4) Do custom construction with your properties

5) return the stack object

In the child class, we inherit from the parent by:

1) Creating an instance of the parent.

over-ride parent function by:

2) over-ride parent function by having a reference to it, super_functionName

3) Then adding a property function of the same name to obj

4) In that function, call the reference super_functionName

5) add custom implementation after that

Now that you have created the parent and child, when using them, simply call the child function
and have it return you an object.

Execute the public properties by calling their names on that object.

Protected properties between parent and child

Pros

– SIMPLICITY: This pattern is very straightforward and easy for beginners to learn.

– Offers truly private and protected members.

– Protects against common javascript pitfalls, specifically if you forget to specify “new” keyword during class creation or if you are using “this” keyword inside functions.

Cons

Requires more memory than Pseudoclassical inheritance pattern. With every new instance of a class memory is reserved for all functions and fields inside that class.

– Types cannot be tested using “instanceof” keyword.

– Javascript minimizers might not perform as good as with Pseudoclassical pattern as there is no way for minimizer to safely rename members of parent class.

Benefits of Prototypal over Functional Inheritance

Prototypal inheritance is all about objects. Objects inherit properties from other objects. That’s all there is to it. There are two ways of creating objects using prototypal inheritance:

Create a brand new object

for example, create object, add properties.

We can calculate the area and the circumference of the circle from its radius:

Now I want to create another circle of radius 10. We create a brand new object by using functionality from our circle object.

Clone an existing object and extend it

JavaScript offers two ways to clone an object:

1) delegation

– Any changes to the prototype are automatically reflected on all its clones.
– Property access is slower because it may need to traverse up the prototype chain.
– Objects may only delegate to a single prototype in JavaScript.

How do we do clone an object via delegation?

Where a is an empty object, and its __proto__ is “someObj”, which will act as the prototype literal object of a.

ref – http://shanghaiseagull.com/index.php/2018/04/13/object-create/

2) concatenation

– Any changes to the prototype need to be propagated to all its clones.
– Property access is faster because inherited properties are copied.
– Objects may copy properties from any number of prototypes.

How do we do clone an object via concatenation?

ECMAscript 6 introduced Object.assign() to achieve this natively in Javascript.

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

example here:

Object.assign

But how is this simple?

We have to call Object.create or Object.assign, and do all these assignment ourselves. Its bother some. The key is to implement creation functions for you like so:

… even better …


— circle —
{ radius: 10 }
{ radius: 5,
create: [Function: create],
area: [Function: area],
circumference: [Function: circumference] }
10

this context, change it via call, bind

Non Strict

In non-strict mode, outside of functions, this is an empty literal object.
global object is called global.

The only difference is that the ‘this’ in functions, is tied to global. While, in strict mode,
the ‘this’ in functions is undefined and not attached to anything.

..or..

Strict mode

In strict mode, the global object is called global. And this is an empty literal object.
However, when you are inside a standalone function, the ‘this’ is undefined and not attached.

or…

Adding properties to global variable

all functions inherit call and apply from Function.prototype

Passing literals instead of objects

If the value passed as this is not an object, an attempt will be made to convert it to an object using the internal ToObject operation.

So if the value passed is a primitive like 7 or ‘foo’, it will be converted to an Object using the related constructor, so the primitive number 7 is converted to an object as if by new Number(7) and the string ‘foo’ to an object as if by new String(‘foo’), e.g.

Bind

Arrow functions

The idea is that arrow functions, when first created, set its this to its enclosing lexical context.
In other words, it retains the value of the this of its enclosing scope.

Let’s try to manipulate it and see if we can change it.

We try to do this by creating a literal object. Then use various ways to bind that object to our foo function’s this.

1) Object calls function

In the literal object, we create a property and have its reference pointing to the arrow function.
Then we simply execute the arrow function via the object’s property like so:


output:
inside arrow function:
{}

As you can see, the “this” in the arrow function does not reference its calling object ‘obj’. It references ‘this’ in its enclosing context.

2) Next, let’s try to bind the “this” in the arrow function to its calling object via call.
We get the reference to the arrow function and execute “call” on it. We would think we can bind the obj in the parameter to foo’s this. However, that is not the case. The ‘this’ in the arrow function is still bound to its enclosing lexical context.

3) This time, we’ll try using bind. We get the reference to the arrow function “foo”, call bind on it, and provide “obj” as the “this”. However, when we call foo, it does not work. It till uses its enclosing lexical context’s “this”.

Therefore, no matter what, foo’s “this”, it is set to what it was when it was created.
Their “this” remains that of the enclosing lexical context.

Returning an arrow function, and evaluating ‘this’

So the point of this example is to show the difference between calling

and

..as both have very different results.

First, let’s define the environment.

We have a literal object obj which has a public property bar. bar is a function that returns
an arrow function that logs “this”.

In the bar function, I also log “this”. That way we can compare.

First, we simply execute the bar function. Because the calling scope is obj, the “this” will belong to literal object “obj”.

Therefore, the logging of “this” will be:


√ bar’s this is:
{ bar: [Function: bar] }

We then execute what bar has returned, which is the arrow function. The output is:


— in arrow function —
{ bar: [Function: bar] }

This is because since the “this” in bar references the literal object “obj”, the arrow function’s this references the enclosing context, which is also “obj”.

In the next example, its the same concept, except we just separate the execution of bar and the arrow function.

Finally, we simply reference the function provided by obj. It does not take into account
of obj. fn2 simply is a reference to the standalone function bar. Whereas before,
variable fn referenced an literal object’s execution of its function.

Thus, if you were call it as a standalone function, your calling scope is global.
Before, in the previous example, the calling scope is the literal object.

For arrow functions, the “this” will always be what it was set to initially.

As an Object Method

this with a getter or setter

ref – https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
ref – http://shanghaiseagull.com/index.php/2018/01/15/getter-setter-js/

Data types, variables for JS

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures
https://www.sitepoint.com/how-to-declare-variables-javascript/

Data types
The latest ECMAScript standard defines seven data types:

Six data types that are primitives

Boolean
Null
Undefined
Number
String
Symbol (new in ECMAScript 6)
and Object

All types (except objects) define immutable values (values, which are incapable of being changed). For example and unlike to C, Strings are immutable. We refer to values of these types as “primitive values”.

Integer type
Size: 8 bytes (2 ^ 64 bits allowed values)
Allowed values: 18437736874454810624 finite numbers (half positive half negative, including positive and negative zero) and three symbolic values NaN, Positive Infinity & Negative Infinity

Integers can be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8) and binary (base 2).

A decimal integer literal consists of a sequence of digits without a leading 0 (zero).
A leading 0 (zero) on an integer literal, or a leading 0o (or 0O) indicates it is in octal. Octal integers can include only the digits 0-7.
A leading 0x (or 0X) indicates a hexadecimal integer literal. Hexadecimal integers can include digits (0-9) and the letters a-f and A-F. (The case of a character does not change it’s value, e.g. 0xa = 0xA = 10 and 0xf = 0xF = 15.)
A leading 0b (or 0B) indicates a binary integer literal. Binary integers can only include the digits 0 and 1.

Some examples of integer literals are:

0, 117 and -345 (decimal, base 10)
015, 0001 and -0o77 (octal, base 8)
0x1123, 0x00111 and -0xF1A7 (hexadecimal, “hex” or base 16)
0b11, 0b0011 and -0b11 (binary, base 2)

Boolean type
Boolean represents a logical entity and can have two values: true, and false.

The Boolean type has two literal values: true and false.

Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object. The Boolean object is a wrapper around the primitive Boolean data type.

If we evaluate “undefined” or “null”, it is false.
If we pass them into a Boolean object, it evaluates to true. This also applies for ‘false’.

For example, the condition in the following if statement evaluates to true:

This behavior does not apply to Boolean primitives. For example, the condition in the following if statement evaluates to false:

Do not use a Boolean object to convert a non-boolean value to a boolean value. Instead, use Boolean as a function to perform this task:

If you specify any object, including a Boolean object whose value is false, as the initial value of a Boolean object, the new Boolean object has a value of true. That’s because an Boolean Object instance does not return primitive true or false. It returns an object and will evaluate to true.

Do not use a Boolean object in place of a Boolean primitive.


output:

its true! 😀
bool is true
bool2 is true
bool4 is true

Null type
The Null type has exactly one value: null. See null and Null for more details.

Undefined type
A variable that has not been assigned a value has the value undefined. See undefined and Undefined for more details.

String types

JavaScript is case-sensitive and uses the Unicode character set.

JavaScript’s String type is used to represent textual data. It is a set of “elements” of 16-bit unsigned integer values.
There are 2^16 (or 0-65535), 0xFFFF representations of text. The encoding is UTF-16, So 0-65535 text representations are mapped from UTF-16. You can view the table at https://upload.wikimedia.org/wikipedia/commons/0/01/Unifont_Full_Map.png
Top is 0 to FF. Left side is 0 to FF. Thus, 0xFFFF is 0-65535.

ref – http://shanghaiseagull.com/index.php/2017/06/07/unicode/

JavaScript strings are immutable (unchangeable), once a string is created it is impossible to modify it. However, it is still possible to create another string based on the original by using string functions such as substr and concat.

An empty string has length zero and therefore contains no elements.

String literal

“string here” + “haha” + etc.

ES6 template literals, as the name suggests, come with a new literal syntax. They use back ticks ( ) to denote the start and end (just like strings use quote marks (‘ ‘ or ” “)). Within those back ticks, Template literals are parsed at runtime, to provide some new features.

A decimal integer literal consists of a sequence of digits without a leading 0 (zero). A leading 0 (zero) on an integer literal, or a leading 0o (or 0O) indicates it is in octal. Octal integers can include only the digits 0-7. A leading 0x (or 0X) indicates a hexadecimal integer literal.

An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ( [] ). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified

The following example creates the coffees array with three elements and a length of three:

If an array is created using a literal in a top-level script, JavaScript interprets the array each time it evaluates the expression containing the array literal. In addition, a literal used in a function is created each time the function is called.

Extra commas in array literals
You do not have to specify all elements in an array literal. If you put two commas in a row, the array is created with undefined for the unspecified elements. The following example creates the fish array:

This array has two elements with values and one empty element (fish[0] is “Lion”, fish[1] is undefined, and fish[2] is “Angel”).

If you include a trailing comma at the end of the list of elements, the comma is ignored. In the following example, the length of the array is three. There is no myList[3]. All other commas in the list indicate a new element.

Note : Trailing commas can create errors in older browser versions and it is a best practice to remove them.

In the following example, the length of the array is four, and myList[0] and myList[2] are missing.

In the following example, the length of the array is four, and myList[1] and myList[3] are missing. Only the last comma is ignored.

Object Literal

An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}).

Additionally, you can use a numeric or string literal for the name of a property or nest an object inside another. The following example uses these options.

console.log(unusualPropertyNames.”); // SyntaxError: Unexpected string
console.log(unusualPropertyNames[”]); // An empty string
console.log(unusualPropertyNames.!); // SyntaxError: Unexpected token !
console.log(unusualPropertyNames[‘!’]); // Bang!

Variables

Declaration: The variable is registered using a given name within the corresponding scope (explained below – e.g. inside a function).

Initialization: When you declare a variable it is automatically initialized, which means memory is allocated for the variable by the JavaScript engine.

Assignment: This is when a specific value is assigned to the variable.

Declaration Types
Note: while varhas been available in JavaScript since its initial releast, letand const are only available in ES6 (ES2015) and up.

This declaration is probably the most popular, as there was no alternative until ECMAScript 6. Variables declared with var are available in the scope of the enclosing function.

Example:

If there is no enclosing function, they are available globally.’

// https://stackoverflow.com/questions/36797206/what-is-the-symbol-primitive-data-type-in-javascript?noredirect=1&lq=1

They prevent using a simple string to reference the field, so only consumers with the symbol can gain access.
So consumers can’t just create a string and access stuff from the object.

In general, symbols are intended as a replacement for magical names. Rather than having a properties simply called ‘foo’, you can allocate a symbol const foo = Symbol() and pass that selectively.

Symbol Type

jQuery lazy loading

Loading the library

Targeting it…and callbacks

Specifying the images

Since your jQuery targets class lazy, we must use lazy for classes on img and div tags.
You use data-src to specify the location of the images.

Note that for img tags, when the images load, it will change to data-src will change to src.
However, if you were to use div, data-src will change to background-image: url(….) .

instanceof

ref – http://shanghaiseagull.com/index.php/2018/02/06/prototype-and-inheritance-in-js-non-class/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof

So we create an instance of CoverArticle called c.
It accesses its own prototype function coverArticleFormat.
It goes up the hierarchy one step and goes into Cover prototype where it accesses coverFormat.
It goes one more step to Image prototype, and accesses print.

Instance of lets you know if your object can access functionalities from the specified Constructor.

Because instance c is at the highest level of the hierarchy. When it can’t find a functionality, it goes down to Cover Prototype Object. When it can’t find it there, it goes to Image Prototype, and fianlly Object Prototype. Hence, it can touch all Prototype Objects of the constructors. That’s why it is true.

When analyze the cover1 instance shown in the diagram, which of prototype Cover, we see that it can access its functionalities from its own Prototype Cover. It can go up to Image Prototype and Object Prototype. However, it ends there. It cannot go backwards and access CoverArticle prototype at all. Hence, false.

isPrototypeOf

isPrototypeOf is a function on the Object Prototype that tests whether the parameter can check against the prototype.
So for example, if we have an instance of CoverArticle (like c) it can definitely touch Cover.
If we have instance of Cover (like cover1) obviously it touches Cover.

buddha, an instance of Image, only touches Image and Object. It cannot go backwards and check Cover Prototype Object. Thus, it will be false.

Why do we use a temporary box in prototype inheritance?

https://stackoverflow.com/questions/47843315/why-do-we-use-a-temporary-box-in-prototype-inheritance

The function below is one that Derek Banas on youtube on his OO Javascript tutorial uses.

You have a function A that you want as a child. You have function B that you want as a parent.
You want to connect them using a function called extend.

The implementation is:

but why is this so?

Prototype objects are single literal objects. We need to create a Temp function that points to the Parent prototype object first, then spawn a instance, which acts as a single literal object.

This single instance will act as the Child’s Prototype Object, which is connected to Parent’s Prototype object.

1) Creating a custom Child Prototype object.

It should be done by like so:

which will give you an empty object with its __proto__ pointing to Foo’s prototype object. However, since we’re gunna do it by hand, we’ll do it step by step.

Setting up Child Prototype Object

First, we create the function Parent. By default, it will have a literal object called Parent Prototype. This Parent Prototype will have __proto__ pointing to default Object Prototype.

– Parent will have a ‘prototype’ reference to Parent Prototype
– Parent Prototype will have a ‘constructor’ reference to Parent

In order to create a Child Prototype Object, we first must create a function Temp to estabblish a Temp setup. The Temp will have a prototype reference to a Temp Prototype object. The Temp Prototype will have a constructor reference back to the temp. And by default, the Temp Prototype will have a __proto__ to the default Object Prototype, as shown in the diagram.

Then, with this setup, if we create an instance of Temp, that instance of Temp, will have its __proto__ pointing to Parent Prototype. We then call this new Temp object “Child Prototype Object”

From here, when we instantiate a child object, it will have its __proto__ pointing to Child Prototype Object. We can access any functions declared there. If it doesn’t exist, it will go up the hierarchy tree via __proto__, which is Parent Prototype. If it does not find it there, it goes up the next __proto__, which is the Object Prototype. And if its not there, then what we’re looking for does not exist.

Object.create

OOP in Javascript (with Node)

ref – http://book.mixu.net/node/ch6.html

The new constructor call (e.g. new Foo()):
creates a new object,
sets the prototype of that object to Foo.prototype and
passes that as this to the constructor.

The prototype chain lookup mechanism is the essence of prototypal inheritance.

Instantiate the class:

Adding private variables

Avoid assigning variables to prototypes

If you want to define a default value for a property of an instance, define it in the constructor function.

Prototypes should not have properties that are not functions, because prototype properties that are not primitives (such as arrays and objects) will not behave as one would expect, since they will use the instance that is looked up from the prototype. Example for Dimitry Sosnikov’s site:

Hence prototypes should only define methods, not data.

static vs non-static

ref – https://stackoverflow.com/questions/45594196/difference-between-static-function-declaration-and-the-normal-function-declarati

That’s the very definition of a static function that you don’t have to instantiate the class to call it. That’s not something JS specific.

A static method is callable from the class itself

A non-static method is callable from an instance of the class, so you basically have to create an object before being able to access that method.

Although in the end, both is just little more than:

es6 classes just make it look nicer. Syntactical sugar.

For example, for a addNumbers(var a, var b) which does return a+b, is it really necessary to waste memory instantiating an object of the class just to add those 2 numbers? No, you just need the result and that’s the whole point of having static.

Using the first style allows you to group methods in a particular class (think of something like namespaces). Maybe you can define classes like Math and String, which both have the add method but implemented in a different way. Calling add() by itself would be confusing, but Math.add() and String.add() are not.