javascript js functions like old class example not ECMAScript 2015 ES6
// 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:1477LW NO topic_id
AD
Další témata ....(Topics)
Inheritance extends - dědění v třídách JavaScript.
Pokud nastane situace, že u několika objektů potřebujeme uložit více údajů a nechceme zasahovat již do základní třídy, můžeme jí rozšířit o další potřídu. Hlavní třídě budeme říkat PARENT (rodič) a podtřídě CHILD (dítě). To že DÍTĚ dědí z určité třídy doložíme výrazem "extends" a název třídy rodiče. Konstruktor RODIČE pak v třídě DÍTĚTE označíme výrazem super() a do závorek vložíme parametry, které bychom zadávali do třídy rodiče. Při vytváření objektu již můžeme použít přímo třídu DÍTĚTE a zadat parametry, které se přes super() dostanou i do třídy RODIČE. DÍTĚ má přístup ke všem privátním funkcím RODIČE, ale i k jeho proměnným (samozřejmě v rámci objektu vytvořeného přes myObjekt = new .....).
class Continent {
constructor(continent) {
this._continent = continent;
}
present() {
return ' is located in ' + this._continent;
}
}
class Country extends Continent {
constructor(continent, country) {
super(continent);
this._country = country;
}
show() {
return this._country + this.present() ;
}
}
myCountry = new Country("Europe", "Czech Republic");
// alert(myCountry.show());
Ke konverzi diakritiky slouží v PHP mnoho funkcí, ale výsledky jsou různé.
Někdy je lepší si udělat vlastní funkci.
Níže uvedená funkce zamění v řetězci paznaky, za jejich čitelný ekvivalent:
Někdy je lepší si udělat vlastní funkci.
Níže uvedená funkce zamění v řetězci paznaky, za jejich čitelný ekvivalent:
/**
* konverze diakritiky - okhelp.cz
*/
function diakritika($vstup) {
$arMala = array('á'=> 'á', 'ÄŤ'=> 'č', 'ÄŹ'=> 'ď', 'Ă©'=> 'é', 'Ä›'=> 'ě',
'Ă'=> 'i', 'Ĺ'=> 'ň', 'Ăł'=> 'ó', 'Ĺ™'=> 'ř', 'š'=> 'š', 'ĹĄ'=> 'ť', 'Ăş'=> 'ú', 'ĹŻ'=> 'ů', 'Ă˝'=> 'ý', 'Ĺľ'=> 'ž' );
$arVelka = array('Ă'=> 'Á', 'Ä©'=> 'Č', 'Ĭ'=> 'Ď', 'É'=> 'É', 'ı'=> 'Ě',
'Ă«'=> 'Í', 'Ň'=> 'Ň', 'Ă"'=> 'Ó', 'Ĺ'=> 'Ř', 'Ĺ '=> 'Š', 'Ť'=> 'Ť', 'ñ'=> 'Ú', 'ĹŽ'=> 'Ů', 'ö'=> 'Ý', 'Ĺ˝'=> 'Ž' );
foreach ($arMala as $key=>$value) {
$vstup = str_replace($key, $value, $vstup);
}
foreach ($arVelka as $key=>$value) {
$vstup = str_replace($key, $value, $vstup);
}
return $vstup;
}
mb_internal_encoding("UTF-8");
$s = 'áčď';
$novy = diakritika($s); // $novy == ačď
/*******************
* převede kůň na kun
* máte možnosti buď si napíšete funkci sami něci jako diakritikaKlasicka($vstup)
* nebo použijete $word = iconv("utf-8", "us-ascii//TRANSLIT", $word);
*ale výsledek otestujte, ne vždy je u iconv uspokojivý
*/
$word = "kůň";
$word = iconv("utf-8", "us-ascii//TRANSLIT", $word);
function diakritikaKlasicka($vstup) {
$arMala = array('á'=> 'a', 'č'=> 'c', 'ď'=> 'd', 'é'=> 'e', 'ě'=> 'e',
'í'=> 'i', 'ň'=> 'n', 'ó'=> 'o', 'ř'=> 'r', 'š'=> 's', 'ť'=> 't', 'ú'=> 'u',
'ů'=> 'u', 'ý'=> 'y', 'ž'=> 'z' );
$arVelka = array('Á'=> 'A', 'Č'=> 'C', 'Ď'=> 'D', 'É'=> 'E', 'Ě'=> 'E',
'Í'=> 'I', 'Ň'=> 'N', 'Ó'=> 'O', 'Ř'=> 'R', 'Š'=> 'S', 'Ť'=> 'T',
'Ú'=> 'U', 'Ů'=> 'U', 'Ý'=> 'Y', 'Ž'=> 'Z' );
foreach ($arMala as $key=>$value) {
$vstup = str_replace($key, $value, $vstup);
}
foreach ($arVelka as $key=>$value) {
$vstup = str_replace($key, $value, $vstup);
}
return $vstup;
}
Tato funkce smaže původní soubor a vytvoří nový.
Parametry jsou cesta k souboru a pole řádků.
Nakonec nastaví mod přístupu k souboru.
Parametry jsou cesta k souboru a pole řádků.
Nakonec nastaví mod přístupu k souboru.
/**
* Tato funkce smaže původní soubor a vytvoří nový.
* Parametry jsou cesta k souboru a pole řádků.
* Nakonec nastaví mod přístupu k souboru.
*
* @param string $fname
* @param array $poleVstup
*/
function createNewFile($fname, $poleVstup)
{ // BEGIN function createNewFile
if(file_exists($fname))unlink($fname);
$fp = fopen($fname, "a");
if (flock($fp, LOCK_EX)) { // do an exclusive lock
foreach ($poleVstup as $key=>$value) {
fwrite($fp, $value); //
}
flock($fp, LOCK_UN); // release the lock
} else {
echo "Couldn't lock the file !";
}
fclose($fp);
chmod($fname, 0777); // set CHMOD
} // END function createNewFile
/**
* fopen() modes
*/
r Read
r+ Read and write, prepend
w Write, truncate
w+ Read and write, truncate
a Write, append
a+ Read and write, append
Od verze PHP 5.1.0 lze k uložení souboru se zámkem využít i funkci file_put_contents
přičemž flag bude mít hodnotu LOCK_EX
int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )
$file = "test.txt";
$content = "Some text which will put into file";
file_put_contents($file, $content, LOCK_EX);
Textarea selection - získání pozice karety kurzoru.
// FOR Gecko Browser selectionStart / selectionEnd selection length
function getPos(){
if (typeof document.getElementById('idTextarea').selectionStart != 'undefined') {
var nPosCursor = document.getElementById('idTextarea').selectionStart;
var nEndPos = document.getElementById('idTextarea').selectionEnd;
return nPosCursor;
}
return 0; // or -1
}
// source by javascript-array.com/guides/javascript_faq/
//Internet Explorer 4+, Mozilla/Gecko/Firefox
function getCaretPos(obj)
{
obj.focus();
if(obj.selectionStart) return obj.selectionStart; //Gecko
else if (document.selection) //Internet Explorer
{
var sel = document.selection.createRange();
var clone = sel.duplicate();
sel.collapse(true);
clone.moveToElementText(obj);
clone.setEndPoint('EndToEnd', sel);
return clone.text.length;
}
return 0;
}
CORS-Cross-Origin-Resource-Sharing Header set Access-Control-Allow-Origin Source Code Example
Usefull Links here
https://www.w3.org/wiki/CORS_EnabledApache .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:09Editace: 7.2.2021 - 09:37
Počet článků v kategorii: 77
Url:javascript-js-functions-example