Özgür Yazılım Nedir?

Kavramsal ve Pratik Açıdan Özgür Yazılım  ve Lisanslar

Kod Gemisi, Eylül 2015
selam@kodgemisi.com

Yazılım geliştirme konusunda genel bilgi sahibi olanlar

Bilişim Çalışanları” veya “Bilgisayar Mühendisliği Öğrencileri*

Sunumun Hedef Kitlesi

* Yazılım mühendisliği, bilgisayar bilimleri, bilişim sistemleri ve benzeri tüm bölümler kastedilmiştir.

Temel Kavramlar

Ekrana üçgen bastıran bir uygulama yazmak isteriz

#include <stdio.h>
 
int main() {
  int n = 10, c, k, space = 1;
  space = n - 1;
 
  for (k = 1; k <= n; k++) {
    for (c = 1; c <= space; c++)
      printf(" ");
 
    space--;
 
    for (c = 1; c <= 2*k-1; c++)
      printf("*");
 
    printf("\n");
  }

  return 0;
}

C dilinde yazılmış bir

kaynak kod (source code)

Derleme

Binary Code

Binary Code

Copyright == Telif Hakkı

©

  • Yazılımlar onu yaratan kişiye teliflidir.
  • Yazılımcı işçiyse, mali hak şirketindir.

©

  • Çoğaltma
  • İşleme
  • Yayma / Satma
  • Değiştirilmesini engelleme
#include <stdio.h>
 
void print (int);
 
int main () {
   int rows = 10;
   print(rows);
   return 0;
}
 
void print (int r) {
   int c, space;
   static int stars = -1;
 
   if (r <= 0)
     return;
 
   space = r - 1;
   stars += 2;
 
   for (c = 0; c < space; c++)
      printf(" ");
 
   for (c = 0; c < stars; c++)
      printf("*"); 
 
   printf("\n");
   print(--r);
}
#include <stdio.h>
 
int main() {
  int n = 10, c, k, space = 1;
  space = n - 1;
 
  for (k = 1; k <= n; k++) {
    for (c = 1; c <= space; c++)
      printf(" ");
 
    space--;
 
    for (c = 1; c <= 2*k-1; c++)
      printf("*");
 
    printf("\n");
  }

  return 0;
}

©

Patent

Recursive fonksiyonlar ile üçgen çizme yönteminizi koruyabilirsiniz.

Patent

  • Türkiye'de ve Avrupa'da yazılımlar patentlenemez!
  • ABD'de... karışık!

Genel olarak karışık ve henüz netleşmemiş

var x;
var y = "Hello JS!";
var z;

x

z

These red boxes are variables,  and each of them has a name (identifier)

undefined
"Hello JS!"
undefined

y

Any JavaScript value can be contained within these boxes

var x;
var y = "Hello JS!";
var z;
z = false;
z = 101;

x

z

undefined
"Hello JS!"
101

y

 

We can assign another value to a variable later after its creation

Curly-brace blocks do not introduce
new variable scopes in JavaScript

// What is i, $, p, and q afterwards?

var i = -1;

for (var i = 0; i < 10; i += 1) {
    var $ = -i;
}
if (true) {
    var p = 'FOO';
} else {
    var q = 'BAR';
}

// Check the next slide for an answer...
var i, $, p, q; // all undefined

i = -1;

for (i = 0; i < 10; i += 1) {
    $ = -i;
}
if (true) {
    p = 'FOO';
} else {
    q = 'BAR';
}

// i=10, $=-9, p='FOO', q=undefined

The code in previous page
actually works like this one:

When the program runs, all variable declarations
are moved up to the top of the current scope.

Reserved Words

Some keywords can not be used as variable names:

null true false break do instanceof typeof
case else new var catch finally return void
continue for switch while debugger function
this with default if throw delete in try
class enum extends super const export import

implements let private public yield
interface package protected static

We don't need to remember them all.   Just be aware of the
possible cause for some SyntaxError exceptions in our program.

Basic Concepts
About Values & Types

value represents the most
basic data we can deal with

Definition

type is a set of data values,
and there are exactly 6 types

Type

value

::  {

}

v1

v2

v3

,

,

...

,

Definition

An object is a
collection of properties

property is a
named container for a value
w/ some additional attributes

The name of a property is called a key;
thus, an object can be considered as
collection of key-value pairs.

There are similar concepts in other programming languages,
e.g., Map, Dictionary, Associative Array, Symbol Table, Hash Table, ...

Definition

To Refer To A Value

  • Literal notation for the value
     
  • Expression involving a variable
    or a property within some object
    to get the value indirectly
     
  • More complex expression involving
    function calls and operators
"Hello!"

y

"test"

x

y

1234

addr: 0x2f4b91

// Value containers
var y = "Hello!";
var w = {
    x: "test",
    y: 1234
};
ref:0x2f4b91

w

A “variable” vs a “property” in an object

// To get the values
y;      // "Hello!"
w;      // (the object ref)
w.x;    // "test"
w['x']; // "test"
w.y;    // 1234
w["y"]; // 1234
var w = {
    x: "test",
    y: 1234,
    z: {},
    w: {},
    "": "hi"
};

Object Initialiser (Object Literal)

The notation using a pair of curly braces
to initialize a new JavaScript object.

var w = new Object();
w.x = "test";
w.y = 1234;
w.z = new Object();
w.w = new Object();
w[""] = "hi";

The code on the left-hand side has exactly the
same result as the one on the right-hand side

Add/Get/Set/Remove A Property

We can dynamically modify an object after its creation

var obj = {
    1  : "Hello",
    "3": "Good",
    x  : "JavaScript",
    foo: 101,
    bar: true,
    "" : null
};

obj["2"] = "World";     // *1 Add & Set
obj["1"];               // *2 Get       -> "Hello"
obj[2];                 // *3 Get       -> "World"
obj[3];                 // *4 Get       -> "Good"
obj.foo = 202;          // *5 Set
delete obj.bar;         // *6 Remove
delete obj[""];         // *7 Remove

Get Property After An Object Literal

JavaScript interpreter will think that we are writing
a “code block” when we start with the “curly braces
as a JavaScript “statement”.

We can to force it to think about “an expression
using the grouping operator.

var w = { x: "test" };
var y = { x: "test" }.x;

w.x;                  // "test"
y;                    // "test"

{ x: "test" }.x;      // SyntaxError: unexpected .

({ x: "test" }.x);    // "test"
({ x: "test" }).x;    // "test"
({ x: "test" })['x']; // "test"
({ x: "test" }['x']); // "test"

NOTE:  Getting a property after an object
literal is not considered a good pattern

Don't Forget Any Value Of The
Object Type Is Actually A “Reference”

var x = { a: 100 };
var y = { a: 100 };
100

a

addr: 0x440892

ref:0x440892

x

100

a

addr: 0x3c980c

ref:0x3c980c

y

Similar to the “pointer” / “address” concept
in programming languages like C or C++

Don't Forget Any Value Of The
Object Type Is Actually A “Reference”

var x = { a: 100 };
var y = { a: 100 };
var z = y;

x === y; // false
y === z; // true
100

a

addr: 0x440892

x

100

a

addr: 0x3c980c

y

z

ref:0x440892
ref:0x3c980c
ref:0x3c980c

Don't Forget Any Value Of The
Object Type Is Actually A “Reference”

var x = { a: 100 };
var y = { a: 100 };
var z = y;

x === y; // false
y === z; // true


z.a = 200;
100

a

addr: 0x440892

x

200

a

addr: 0x3c980c

y

z

ref:0x440892
ref:0x3c980c
ref:0x3c980c

Don't Forget Any Value Of The
Object Type Is Actually A “Reference”

var x = { a: 100 };
var y = { a: 100 };
var z = y;

x === y; // false
y === z; // true


z.a = 200;

x.a; // 100
y.a; // 200
z.a; // 200
100

a

addr: 0x440892

x

200

a

addr: 0x3c980c

y

z

ref:0x440892
ref:0x3c980c
ref:0x3c980c

Disambiguate According To The Context

When we refer to a “Variable”, a “Property”, a “Symbol”, or
an “Identifier”, we might actually mean the concept of:

  • The “symbol” itself (which is just a “name”)
  • The named “container” which can store any value
  • The “value” stored inside the named container

 

When we use the word “Object”, it might be the concept of:

  • A “value” of the Object type (which is a “reference”)
  • An “object” that can be referenced by a value of the Object type
  • The Object “type
  • The “standard built-in ECMAScript object” named “Object”

Some Objects Are
Called “Functions”

Functions Are
Called “Methods”
In Some Cases

Definition

function is an object
that is callable

var a = 7;
var sayhi = function (name) {
    var a = "Hello " + name;
    console.log(a);
    return a;
};

Function Expression

The notation using the keyword “function
followed by an argument list and a code block
to create/initialize a JavaScript Function object

Any function in JavaScript is first-class, which can be assigned
to a variable or passed as an ordinary value to another function.

Function Invocation

A pair of parentheses invokes the preceding function;
the values of zero or more arguments are passed in.

Each time a function is called/invoked, it has its own variable scope
with local variables and arguments filled with corresponding values

var a = 7;
var sayhi = function (name) {
    var a = "Hello " + name;
    console.log(a);
    return a;
};

sayhi("J"); // "Hello J"
a; // 7

When # of Arguments Not Matched

In JavaScript, it is OK to invoke a function
with a mismatched number of arguments.

At run time, any argument without passing a value is filled with the
undefined” value, just like a local variable without any assignment.

var f = function (a, b) {
    console.log(typeof b);
    return a + b;
};

f(3);       // NaN ("undefined" printed)
f(3, 4);    // 7   ("number" printed)
f(3, 4, 5); // 7   ("number" printed)

Function Not Returning A Value

A function does not necessarily
need to return a value explicitly.

When that is the case, the “undefined” value is returned.

var f = function () {
    return;
};

var g = function () {
};

var foo = f();
foo; // undefined
g(); // undefined

Function Expression Can Be Named

var fact = function (n) {
    if (n === 0) return 1;
    if (n > 0) return n * fact(n - 1);              // *1
};
fact(3);     // 6, which is the factorial of 3

var fact2 = fact;
fact = null; // But if the value changes...
fact2(3);    // TypeError: “null” is not function



var f = function fib(n) {
    if (n === 0) return 0;
    if (n === 1) return 1;
    if (n > 1) return fib(n - 1) + fib(n - 2);      // *2
};
f(10);       // 55

var g = f;
f = null;    // If the value changes...
g(10);       // 55  (still working)

The name “fib” is accessible
only inside the function itself

Function Declaration Statement (1/2)

// We can invoke a function
// before its "declaration"
//
// Please see the next slide for the reason......


var x = 100;

plusOne(x); // 101
plusOne(y); // NaN

var y = 999;

function plusOne(n) {
    return n + 1;
}

This is a “function declaration
statement that requires a “name

Functions can be used before their function declaration statements, because...

Function Declaration Statement (2/2)

var x, y, plusOne;       // Variable declarations

plusOne = function (n) { // Function declarations
    return n + 1;        // are also moved to the
};                       // top of current scope

x = 100;

plusOne(x); // 101
plusOne(y); // NaN

y = 999;

When program runs, all function declarations
are moved up to the top of the current scope,
as well as all variable declaration statements.

When the program runs, those function declaration statements work like this:

Invoke After A Function Expression

JavaScript interpreter will think that we are writing a
function declaration” when we start with the keyword
function” as a JavaScript “statement”.

We can to force it to think about “an expression” using the grouping operator.  In fact, any appropriate operator would
work just fine if you do not care about the return value.

(function () {
    return 123;
}());                                    // 123


(function(){ return 'hi'; })();          // "hi"
!function(){ console.log('ya'); }();     // true
void function(){ console.log('ya'); }(); // undefined

Definition

method is a function
as some object's property

The property which contains a value that
references to some function is called a “method.”


So is the referenced function.

// The cat object has three properties
// cat.age, cat.meow, and cat.sleep

var cat = {
    age: 3,
    meow: function () {}
};
cat.sleep = function () {};

// We would say that cat.meow and
// cat.sleep are "methods" of cat

Methods of An Object

When a function is invoked as a method of
some object, the this value during the function
call is (usually) bound to that object at run-time

Refer To The Object Inside A Method

var cat = {
    age: 3,
    meow: function () {
        console.log(this.sound);
        return this.age;
    },
    sound: 'meow~~'
};

cat.meow(); // 3  ("meow~~" is printed)

var m = cat.meow;
m(); // TypeError or undefined

Closures

Definition

closure is a pair of
a function and an environment
for resolving free variables

When we use non-local variables...



    var a = 1;
    var closureFunc = function () {
        // The "environment" (the outer scope)
        // determines to which value does the
        // symbol `a` resolve here
        console.log(a);
        return a;
    };

The Lexical Environment (1/3)



    var a = 1;
    var closureFunc = function () {
        // The "environment" (the outer scope)
        // determines to which value does the
        // symbol `a` resolve here
        console.log(a);
        return a;
    };


    closureFunc(); // 1

    a = 100;
    closureFunc(); // 100

    a = 'hello';
    closureFunc(); // 'hello'

When we use non-local variables...

The Lexical Environment (2/3)

The Lexical Environment (3/3)



    var a = 1;
    var closureFunc = function () {
        // The "environment" (the outer scope)
        // determines to which value does the
        // symbol `a` resolve here
        console.log(a);
        return a;
    };



    var anotherFunc = function () {
        var a = 2;
        return closureFunc();
    };

    anotherFunc(); // 1

The “environment” is determined at creation-time, not at run-time

Lexical scope

Dynamic scope
(not for JavaScript)

Which variable is the identifier “a” here
bound to when the function is invoked?

var getClosureFunc = function () {

    var a = 1;
    var closureFunc = function () {
        // The "environment" (the outer scope)
        // determines to which value does the
        // symbol `a` resolve here
        console.log(a);
        return a;
    };

    return closureFunc;
};


var a = 3;
var clsr = getClosureFunc();

clsr(); // 1

Common Way To Create A Closure (1/3)

A function that returns a closure function...

A closure is created each time
getClosureFunc returns.

var getClosureFunc = function () {

    var a = 1;
    return function () {
        // The "environment" (the outer scope)
        // determines to which value does the
        // symbol `a` resolve here
        console.log(a);
        return a;
    };


};


var a = 3;
var clsr = getClosureFunc();

clsr(); // 1

A function that returns a closure function...

Common Way To Create A Closure (2/3)

A closure is created each time
getClosureFunc returns.

var clsr = (function () {

    var a = 1;
    return function () {
        // The "environment" (the outer scope)
        // determines to which value does the
        // symbol `a` resolve here
        console.log(a);
        return a;
    };


}());


var a = 3;


clsr(); // 1

A function that returns a closure function...  gets invoked immediately

Common Way To Create A Closure (3/3)

A closure is created when the
anonymous function returns.

How a variable/identifier/symbol inside a function will be
resolved
for all function calls in the future is completely
determined at the creation-time of the function already

 

except for “this”.

JavaScript Uses Static/Lexical Scope Model

Lifetime of A Lexical Scope/Environment

The lifetime of the local variables (the environment/scope) does
not necessarily end as the function returns.  If there is any local variable referenced by a returned function, a closure is created.
Only the returned functions can access those hidden private states.

var x = 999;

var f = function () {
    var x = 222;            // *1
    return function () {
        x += 100;
        return x;           // *2
    };
};

var g = f();                // *3
g();        // 322          // *4
g();        // 422          // *5

Rethinking Named Function Expressions

named function expression creates a closure
with the free variable of that name bound to the function itself.

var f = function fac(n) {
    if (n === 0) return 1;
    if (n > 0) return n * fac(n - 1);
};

//----- The above code works like: -----

var f = (function () {

    var fac = function (n) {
        if (n === 0) return 1;
        if (n > 0) return n * fac(n - 1);
    };

    return fac;

}());

Some Objects Are
Called “Arrays”

var w = [
    "test",
    1234,
    {},
    [],
    "hi"
];

w[4]; // "hi"

Array Initialiser (Array Literal)

The notation using a pair of square brackets
to create/initialize a JavaScript Array object.

var w = new Array(5);
w[0] = "test";
w[1] = 1234;
w[2] = new Object();
w[3] = new Array();
w[4] = "hi";


w[4]; // "hi"

The code on the left-hand side has exactly the
same result as the one on the right-hand side

Append New Elements To An Array

var arr = [ "test", 1234, {}, [], "hi" ];

arr.push("sixth"); // 6
arr.length;        // 6
arr[5];            // "sixth"

arr[7] = 012;      // 10
arr.length;        // 8

arr[6];            // undefined
arr[7];            // 10

arr[8];            // undefined
arr.length;        // 8

There is a method “push” for all Array objects.
Or you can just assign a value to the corresponding slot.

Enumerate All Elements In An Array (1/3)

var arr = [ "test", 1234, {}, [], "hi" ];

for (var i = 0; i < arr.length; i += 1) {
    console.log(arr[i]);
}

There is a special property “length” for any Array object.

NOTE:  A “For-loop” is not always recommanded
for enumerating all elements in an array, because...

Enumerate All Elements In An Array (2/3)

var arr = [ "test", 1234, {}, [], "hi" ];

arr.forEach(function (val /*, i, arr*/) {
    console.log(val);
});
// undefined

There is a special method “forEach” for any Array object.

The “forEach” method is much nicer...

Enumerate All Elements In An Array (3/3)

var arr = [ "test", 1234, {}, [], "hi" ];

arr.map(function (val /*, i, arr*/) {
    return typeof val;
});
// [ "string",
//   "number",
//   "object",
//   "object",
//   "string" ]

There is a special method “map” for any Array object.

We even have functional “map”, “every”, “some”, ...   See the notes for more info

Calling Object.keys( ... ) gives you all enumerable “keys” in an object

How You Can Enumerate An “Object” (1/2)

var obj = { a: "test", b: 1234, c: "hi" };

Object.keys(obj); // [ "a", "b", "c" ]

Calling Object.keys( ... ) with map gives you all enumerable “values

How You Can Enumerate An “Object” (2/2)

var obj = { a: "test", b: 1234, c: "hi" };

Object.keys(obj).map(function (key) {
    return obj[key];
});
// [ "test",
//    1234,
//    "hi" ]

Class-free OOP
In JavaScript

 

with Prototypal Inheritance

Review The Data Types We've Seen So Far

Undefined

Null

Boolean

Number

String

Object

There are exactly 6 types
of values in JavaScript

Review The Data Types We've Seen So Far

Undefined

Null

Boolean

Number

String

Object

These 2 are pretty boring

Review The Data Types We've Seen So Far

Undefined

Null

Boolean

Number

String

Object

These 3 are more useful primitives

Review The Data Types We've Seen So Far

Undefined

Null

Boolean

Number

String

Object

This is the most interesting data type
where we can start having nested and
organized program structures

tmp

By KodGemisi

tmp

A concise and accurate JavaScript tutorial/notes written for those entering the JavaScript world for the first time but already have experience with other languages

  • 349