Okhelp.cz

Recepty, články, nápady, programování. Dříve dum-zahrada, finance, internet a know-how.okhelp.cz Pro lepší výsledky hledání používejte i diakritiku.

javascript js functions like old class example not ECMAScript 2015 ES6


AD MOB


// IF variable is not defined (or has a falsey value) THEN set it to an empty object.
// ELSE do nothing (technically speaking, variable gets assigned to itself)
var variable = variable  ||  {} ;

function test(){
   console.log(1);
}
// when called
test(); // 1
// or
var a = test;
a(); // 1

// or autocall if code executed
var test2 = function(){
  console.log(2);
}
// test2 is undefined because the function test2 has no return value

// return string
function stringTest(param) {
    return 'Hello ' + ' ' + param;
}

console.log(stringTest("Alice"));  // Hello Alice

// return number
function numberTest(param) {
    return 6 + param;
}

console.log(numberTest(5));  // 11



// or autocall if code executed 
// function is like other variables
// parenthesis is for made groups or call functions.
// Immediately-Invoked Function Expression,
// or IIFE for short. It executes immediately after it’s created.
(function(){
  // all your code here
  var foo = function() {};
  window.onload = foo;
  // ...
})();

// foo is unreachable here (it’s undefined)

//////////////////////////////
// IIFE Immediately Invoked Funtion Expression
var greeting = function(name) {
    return 'Hello ' + ' ' + name;
}('John');

console.log(greeting);  // Hello John
console.log(typeof greeting);  // string
console.log(greeting('Suzan'));  // Uncaught TypeError: greeting is not a function




///////////////////////
var val = (function(){
     var a = 0;  // in the scope of this function
     return function(x){
         a += x;
         return a;
     };
})();

alert(val(10)); //10
alert(val(11)); //21

///////////////////////
// create the structure

var testHash = {
   a : 1,
   b : function(){
      console.log(4);
   },
   c: function(param){
	   var num = param +5;
	   return num;
   }
}
console.log(testHash.a); // 1
testHash.b(); // 4
testHash['b'](); // 4
testHash.c(7); // 12

/////////////////////////
// or function like class
function TestClass(n) {
    this.some_property = n;
    this.some_method = function() {
       console.log(this.some_property);
    };
}

var foo = new TestClass(3);
var bar = new TestClass(4);
foo.some_method(); // 3
bar.some_property += 2;
bar.some_method(); // 6
// console.log(some_property); // Uncaught ReferenceError: some_property is not defined


//////////////////////////
function Car(brand, year) {
	return {
		brand: brand,
		year: year
	}
}
var honda = Car("Honda", 1999); 
console.log(honda.brand); // Honda
console.log(honda.year);  // 1999 

honda.brand = "Honda new Generation";
honda.year = 2021; 
console.log(honda.brand); // Honda new Generation
console.log(honda.year); // 2021

var mazda = Car("Mazda",1987);
console.log(honda.brand); // Honda new Generation
console.log(mazda.brand); // Mazda

//////////////////////////////////////
// simplified code 

 var TEST_CLASS = TEST_CLASS || {};

TEST_CLASS.pokus = TEST_CLASS.pokus || (function() {
    // -------------------------------------------------------------------------
    // Private static variables and methods
    // -------------------------------------------------------------------------
    
    var privateStaticNumber = 5;
    var privateStaticString = "My privateStaticString: ";
    var privateStaticArray = [];

	function privateStaticMethod(){
		console.log('privateStaticMethod');
	}

	// CONSTRUCTOR CTOR
	return function(config) {
		 // ----- private variables -----

        var me = this,
        isPaused = false;
		this.privateStaticNumber = config.firstParam;
		this.privateStaticString = privateStaticString + config.secondParam; // += produce: undefined I am from secondParam
		this.privateStaticArray = config.thirtParam;
			
		// ----- private methods -----
        function getMode (mode, speed) {
			// document.getElementById(mode).addEventListener('click', function () { snakeSpeed = speed; });
		}
		
		// ----- public variables -----
        me.correct = 0;
        me.wrong = 0;
		
		// ----- public methods -----
        
        me.setString = function(val) {
            this.privateStaticString = val;
        };
        me.getString = function() {
            return this.privateStaticString;
        };
		me.publicMethod = function(param){
			console.log(param + ' from me.publicMethod()');
		};

	
	}; // end CTOR
})();
// end TEST_CLASS.pokus


var _me = _me || {};
var _me_test = new TEST_CLASS.pokus({firstParam:8, secondParam:" I am from secondParam", thirtParam:[1,3,9]});
// TEST_CLASS.pokus.privateStaticMethod(); // is not a function
// TEST_CLASS.pokus.publicMethod("Hola!"); // TEST_CLASS.pokus.publicMethod is not a function
// TEST_CLASS.publicMethod("Hola hej!"); // TEST_CLASS.publicMethod is not a function
 
// TEST_CLASS.pokus.publicMethod(" Hello!"); // is not a function
_me_test.publicMethod(" Hello!"); //  Hello! from me.publicMethod()
console.log( _me_test.getString()); // My privateStaticString:  I am from secondParam
console.log( _me_test.isPaused); // undefined
 
Date: 04.11.2020 - 23:14

77LW NO topic_id




AD

Další témata ....(Topics)


70

PHP Měření času microtime | php-mereni-casu


Jak změřit čas trvání vykonání nějaké funkce, nebo provedení části kódu v PHP


$start_time = microtime(true);

// do some work

$end_time = microtime(true);
// Calculate  execution time
$execution_time = ($end_time - $start_time);

echo " Execution time = ".$execution_time." sec";

Date: 11.06.2020 - 09:14
20

PHP Cesta k souboru se šipkami | php-cesta-k-souboru-se-sipkami


Pro orientaci návštěvy na Vašem webu je tu funkce v PHP, která rozepíše cestu k právě otevřenému souboru do menu, kde jsou jednotlivé části odděleny dvojšipkou:



Path with arrows

Path with arrows - PHP functions make menu when is every folder on files path as links separated double arrows

function PathWithArrows () {
   $root = '//moje-stranky.cz';
   $cesta = explode('/', $_SERVER["PHP_SELF"]);
   $cestaPomociSipek = "";
   $home = "";
   $n = 0;
   foreach ($cesta as $str)
   {
  
   	 if($n == 0){
   	 	$home = '<a href="'.$root.'">home</a>';
  
   	 $n++;
   	 continue;
   	 }
   	 if($str !== ""){
  
   	  $root .= '/'.$str;
      $cestaPomociSipek .= ' » <a href="'.$root.'"> $str </a> ';
     }

   }
   return $home.$cestaPomociSipek;
} 
11

Sqlite databáze základní příklad PHP | sqlite-databaze-zakladni-priklad-php-id-2292


Kontrola zda database existuje, zmena opravneni, vytvoreni nove, nebo jeji otevreni kdyz existuj

$path_to_database = "CESTA_K_SOUBOURU/database.sqlite";

// zmena opravneni / chmod permission 

if(file_exists($path_to_database))
  chmod($path_to_database,01777);

// otevreni , vytvoreni databaze
  $db = new SQLiteDatabase($path_to_database);
vlozeni tabulky s nazvem test, mozno bezpecne vkladat text v UNICODE

$db->query("
CREATE TABLE test
(url VARCHAR(55),
title VARCHAR(55),
keywords VARCHAR(500),
content_of_page VARCHAR(2500),
date DATE(50),
revision DATE(50),
visit INTEGER(8),
PRIMARY KEY (url),
UNIQUE (url))");
// vlozeni dat do tabulky test
 $query = $db->query("INSERT INTO test (url,title,keywords,date,c,visit) VALUES (""
  .$url."",""
  .$title."",""  
  .$"keywords."",""
  .$datum."",""
  .$text_of_page."",""    
  ."1"."")", $error);
// update tabulky / radku, prepis jiz existujicich dat
 $query = $db->query("UPDATE test SET   $query = $dbb->query("UPDATE test SET obsah="".$text_novy
  ."", title="".$title_new
  ."", keywords="".$keywords_new
  ."", revision="".date("j.n.Y - H:i")  
  ."" WHERE url="".$url.""", $error);
  }
  if (!$query) {
      exit("Error in query: "$error"");
  } else {
      echo "Number of rows modified: ", $dbb->changes();

  }
// vyber vsech dat z tabulky test

$resss = $db->unbufferedQuery("SELECT * FROM test"); 
// prochazeni vysledku vyberu z tabulky
foreach ($resss as $row) { // iterate through result object 
  print  $row["url"];
  print  $row["title"];
  // atd. .... etc. .... 
} // end foreach
// presne hledani v tabulce nebo substring / pokud hledame jen substring tak dame % pred pokude ma byt cokoliv vpredu, nebo za pokud vzadu // pokud jsou procenta vpredu i vzadu, tak najde napriklad predblablavzadu
$resss = $db->unbufferedQuery("SELECT * FROM test WHERE title LIKE %blabla%");
// ziskat setrideny vyber a max pocet vybranych poloze / na konec dotazu pridame:
ORDER BY title DESC LIMIT 50
// setridi podle tituku a vybere 50 radku // smazani urciteho radku dle obsahu nektereho ze sloupcu
$ur = "www.domena.com/blahblah.php"
 $query = $dbb->query("delete from test where url like "$ur"");
36

PHP html code | php-html-code


V php se nevyhnete znalosti html kodu. Zde je šablona pro vytvoření kostry stránky. Charset UTF-8 zvládají všechny moderní prohlížeče, ale je nutné, aby soubor na serveru byl uložen v tomto formátu, jinak by došlo ke zkomolení diakritiky. Pokud budete používat jen češtinu na stránkách, můžete nastavit charset na "windows-1250", ale v dnešní době je to již krok zpět.

Pokud chceme zobrazit zdrojový kód určitého php souboru můžeme použít funkce show_source(__FILE__);

 show_source(__FILE__); 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="description" content="zde bude popis stranky">
  <meta name="keywords"    content="zde, budou, klicova, slova, oddelena, carkou">
 
<title>Nazev stranky</title>
  </head>
  <body>
   <!--text a kod stranky-->

  </body>
</html>

73

PHP CORS Cross Origin access control allow origin example html | php-cors-cross-origin-access-control-allow-origin-example-html


CORS-Cross-Origin-Resource-Sharing Header set Access-Control-Allow-Origin Source Code Example

Usefull Links here

https://www.w3.org/wiki/CORS_Enabled

https://www.moesif.com/blog/technical/cors/Authoritative-Guide-to-CORS-Cross-Origin-Resource-Sharing-for-REST-APIs/

Apache .htaccess Allow File Types


<IfModule mod_setenvif.c>
  <IfModule mod_headers.c>
    <FilesMatch ".(bmp|cur|gif|ico|jpe?g|png|svgz?|webp)$">
      SetEnvIf Origin ":" IS_CORS
      Header set Access-Control-Allow-Origin "*" env=IS_CORS
    </FilesMatch>
  </IfModule>
</IfModule>

.htaccess which is closest to the file!!!!!

Date: 17.06.2020 - 08:09


Editace: 7.2.2021 - 09:37
Počet článků v kategorii: 77
Url:javascript-js-functions-example

AD
11 Share
Share
Tweet