• Home
  • About
    • Artyrie's Blog photo

      Artyrie's Blog

      Artyrie, Ruri

    • Learn More
    • Email
    • Twitter
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects

JavaScript Basic2

06 Nov 2019

Reading time ~8 minutes

JavaScript

•	This page is my note about javascript.
•	It will be difficult to read.
•	Comment : //

Caution : Ungly English
Sample code is almost reffered in 생활코딩

important concept of programming

•	Class : design to make object.
•	Object : making target in software world.
•	Instance : maked detail substance in software world by design.

JavaScript as functional Language

Scope

var gscope = 'global variable';
function fscope(){
    lscope ='local';
}
function main(){ 
    for(var i=0; i<5; i++){ 
        var temp = i; 
    }
console.log(temp); 
} 
main();

Scope is different to the other language.
JS’s local variable in function is usable until function ends.
So, console.log(temp) works well.

var i = 5;
function a(){
    var i = 10;
    b();
}
function b(){
    document.write(i);
}
a();

This result is 5.
function scope is only in function.
you must test this point.
variable priority is local variable.
refer this lecture blog

MYAPP = {}
MYAPP.calculator = {
    'left' : null,
    'right' : null
}
MYAPP.coordinate = {
    'left' : null,
    'right' : null
}
 
MYAPP.calculator.left = 10;
MYAPP.calculator.right = 20;
function sum(){
    return MYAPP.calculator.left + MYAPP.calculator.right;
}
document.write(sum());

If you have to use global variable,
you can make object for controlling the variables that you may make global.
Even you don’t want to use global variable,

(function(){
    var MYAPP = {}
    MYAPP.calculator = {
        'left' : null,
        'right' : null
    }
    MYAPP.coordinate = {
        'left' : null,
        'right' : null
    }
    MYAPP.calculator.left = 10;
    MYAPP.calculator.right = 20;
    function sum(){
        return MYAPP.calculator.left + MYAPP.calculator.right;
    }
    document.write(sum());
}())

you can modulize your code using unnamed function.
This is formal way for modulization.

Property of function

function cal(func, num){
    return func(num)
}
function increase(num){
    return num+1
}
function decrease(num){
    return num-1
}
alert(cal(increase, 1));
alert(cal(decrease, 1));

Actually function is object.
So, function can be value and pass as value.
It is also used as return value or array of value.

function sortNumber(a,b){
    return b-a;
}
var numbers = [20, 10, 9,8,7,6,5,4,3,2,1];
alert(numbers.sort(sortNumber)); // array, [20,10,9,8,7,6,5,4,3,2,1]

if variable is placed where front of ‘.’, It is object.
numbers.sort(); <- numbers is array object.
array object has sort method.

•	 Function is partition of code what has independent function
•	 Method is some function which is included in class / structure / ect.
var numbers = [20, 10, 9,8,7,6,5,4,3,2,1];
numbers.sort()
// [1, 10, 2, 20, 3, 4, 5, 6, 7, 8, 9] sorted as string;

Syntax of array is array.sort(sortfunc:optional)
Basically, It sorts by string (alphabet).
Number was made as string, so 10 is front of 20.
So, use sortfunc to decide priority of sorting.

var numbers = [20, 10, 9,8,7,6,5,4,3,2,1];
var sortfunc = function(a, b) {
	console.log(a,b);
	return a-b; // return b-a <- reverse sort
}
numbers.sort(sortfunc);

Using call back sample

{"title":"JavaScript","author":"egoing"}
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<script type="text/javascript">
    $.get('./datasource.json.js', function(result){
        console.log(result);
    }, 'json');
</script>
</body>
</html>

this code from 생활코딩

Inner function

function outter(){
    var title = 'coding everybody';  
    function inner(){        
        alert(title);
    }
    inner();
}
outter();

Inner function that is in function can use local variable
in outter function.

Closure

function outter(){
    var title = 'coding everybody';  
    return function(){        
        alert(title);
    }
}
inner = outter();
inner();

inner = outter(); ends, local variable in function outter
disappears because of outter(); is end.
but as a result of inner();, alert ‘coding everybody’.
Why? local variable didn’t disappear.
outter function doens’t disappear until inner function ends

function factory_movie(title){
    return {
        get_title : function (){
            return title;
        },
        set_title : function(_title){
            title = _title
        }
    }
}
ghost = factory_movie('Ghost in the shell');
matrix = factory_movie('Matrix');
 
alert(ghost.get_title());
alert(matrix.get_title());
 
ghost.set_title('공각기동대');
 
alert(ghost.get_title());
alert(matrix.get_title());

There is some property.

•	 closure can makes class.
•	 It can make private declaring way // JS doens't have.
•	 When outter function is executed, generate new closure.
•	 So,  It can be independent object.
•	 In this code, passed title only can be controlled by method.

Advanced Closure

var arr = []
for(var i = 0; i < 5; i++){
    arr[i] = function(){
        return i;
    }
}
for(var index in arr) {
    console.log(arr[index]());
}

arr[index] has just return i. So, i=5.
result : repeat 5, 5 times

var arr = []
for(var i = 0; i < 5; i++){
    arr[i] = function(id) {
        return id;
    }
}
for(var index in arr) {
    console.log(arr[index]());
}

This code shows undefined 5 times.
Why? function(id) need a parameter id.
but we didn’t give parameter id.

var arr = []
for(var i = 0; i < 5; i++){
    arr[i] = function(id) {
		return id;
    }(i); // function(i);
}
for(var index in arr) {
    console.log(arr[index]); // arr[index] is not function.
	// because arr[index] has retuned id value that i.
}

So, this is correct way.
but we can use closure, too.

var arr = []
for(var i = 0; i < 5; i++){
    arr[i] = function(id) {
        return function(){
            return id;
        }
    }(i);
}
for(var index in arr) {
    console.log(arr[index]());
}

I think this way is no essential.
Just showing possible.

Hidden varialbe in function

function sum(){
    var i, _sum = 0;    
    for(i = 0; i < arguments.length; i++){
        document.write(i+' : '+arguments[i]+'<br />');
        _sum += arguments[i];
    }   
    return _sum;
}
document.write('result : ' + sum(1,2,3,4));

arguments similar to array and It’s values is passed arguments.
So, arguments is [1,2,3,4]
arguments is instance of arguments object. Thus this property, what function need 2 parameters and
we pass 1 parameter, then function.length is 2 and arguments,length is 1
arguments is number of passed parameter.
function.length is number of variables that function needs.

Calling the function

JavaScript’s function is object.
So,

function sum(arg1, arg2){
    return arg1+arg2;
}

this function; sum is instance of function object.
So sum can call method of function.
like sum.apply(null, [1,2])

o1 = {val1:1, val2:2, val3:3}
o2 = {v1:10, v2:50, v3:100, v4:25}
function sum(){
    var _sum = 0;
    for(name in this){
        _sum += this[name];
    }
    return _sum;
}
alert(sum.apply(o1)) // 6
alert(sum.apply(o2)) // 185

sum.apply(o1) makes sum to method of o1 object
and call sum and delete sum.
o1.sum = sum; -> function definition

Objective JavaScript

Object : Class

var person = {
    'name' : 'egoing',
    'introduce' : function(){
        return 'My name is '+this.name;
    }
}
document.write(person.introduce());

This code can’t recycle.

function Person(name){
    this.name = name;
    this.introduce = function(){
        return 'My name is '+this.name; 
    }   
}
var p1 = new Person('egoing');
document.write(p1.introduce()+"<br />");
 
var p2 = new Person('leezche');
document.write(p2.introduce());

Define property of object in constructor ‘new’.
So, we can recycle this code.

Global object is property of window property.
window.func(); can execute.

Special property of this object

var funcThis = null; 
function Func(){
    funcThis = this;
}
var o1 = Func();
if(funcThis === window){
    document.write('window <br />');
}
var o2 = new Func();
if(funcThis === o2){
    document.write('o2 <br />');
}
//window
//o2

This depends on your code that It indicates what.
So when the function called, this indicates window object.
But method of this indicates it’s object.

Function has method from the first

Every function has method that is not written by user.
Note important 3 method.

•	call
•	bind
•	method
var example = function (a, b, c) {
  return a + b + c;
};
example(1, 2, 3);
example.call(null, 1, 2, 3);
example.apply(null, [1, 2, 3]);

These are ways that calls function.
Argument null alternate this
What is different that calling function is on code.

var obj = {
  string: 'zero',
  yell: function() {
    alert(this.string);
  }
};
var obj2 = {
  string: 'what?'
};
obj.yell(); // 'zero';
obj.yell.call(obj2); // 'what?'

Use call with obj2, this of this becomes obj2.
Thus prints what?

It can use function of the other object.

Where we use it?
When arguments is controlled, we need it.
Arguments is similar to array, explained before.

function example3() {
  console.log(Array.prototype.join.call(arguments));
}
example3(1, 'string', true); // '1,string,true'

It can use this way.
Arguments is not array. So, use this way.
More information : Zerocho


Inheritance

Prototype

function Ultra(){}
Ultra.prototype.ultraProp = true; 
function Super(){}
Super.prototype = new Ultra();
function Sub(){}
Sub.prototype = new Super();
 var o = new Sub();
console.log(o.ultraProp); // true

Prototype is original of object.
It is special property of object.
Saved data in prototype is connected,
when the constructor new makes new object.
Prototype is chain that connects between object and the other object.

Inheritance

function Person(name){
    this.name = name;
}
Person.prototype.name=null;
Person.prototype.introduce = function(){
    return 'My name is '+this.name; 
} 
function Programmer(name){
    this.name = name;
}
Programmer.prototype = new Person();
Programmer.prototype.coding = function(){
    return "hello world";
}
 var p1 = new Programmer('egoing');
document.write(p1.introduce()+"<br />"); // My name is egoing
document.write(p1.coding()+"<br />"); // hello world

Programmer inherited Person.
So, It can use person’s method and new own method.
It is different form of class Person extends Programmer

Standard Built-in Object

JavaScript has built-in object.

•	Object
•	Function
•	Array
•	String
•	Boolean
•	Number
•	Math
•	Date
•	RegExp
Array.prototype.rand = function(){
    var index = Math.floor(this.length*Math.random());
    return this[index];
}
var arr = new Array('seoul','new york','ladarkh','pusan', 'Tsukuba');
console.log(arr.rand());

This code is expansion of array.
Output of this function is random value in array.

Expansion of Object

We can make API that all of object approaches by expanding object.

Object.prototype.contain = function(neddle) {
    for(var name in this){
        if(this[name] === neddle){
            return true;
        }
    }
    return false;
}
var o = {'name':'egoing', 'city':'seoul'}
console.log(o.contain('egoing'));
var a = ['egoing','leezche','grapittie'];
console.log(a.contain('leezche'));

We can make contain method.
But, this way is bad because of confusion of development.
if you want to check this property contain is function’s own property,
use this hasOwnProperty(object.what)



Java Script Share Tweet +1