JavaScriptとgrid

JavaScript Class

JavaScript Classes

A class is a type of function, use the keyword of class. When the class to be created, always need a constructor() method.

↑ onload="showResize()" を加えてresize していなくてもwindow size が表示されるように。reloadだと消える。


class Car {
 constructor(name) {
  this.carname = name;  //this を使わないとobjectを呼び出せない(?から?)
 }
 present(y) {
  return y + ", We have a " + this.carname;
 }
}

thecar = new Car("Saab");
document.getElementById("CMethod").innerHTML =
thecar.present("Yes");

Date reference

JavaScript Class Inheritance

Use the "extends" keyword to inherit all methods from another class.
Use the "super" method to call the parent's constructor function.

//extends and super()
class Car1 {
 constructor(brand) {
  this.carname1 = brand;
 }
 presntt1() {
  return 'We have a ' + this.carname1;
 }
}

class Model extends Car1 {  //extends "class name"
 constructor(brand, year) {
  super(brand); //inherit property and method
  this.model = year;
 }
 show() {
  return this.presntt1() + ', it was made  ' + this.model;
 }
}
thecar1 = new Model("Mustang", 1998);
document.getElementById("extendsSuper").innerHTML = thecar1.show();

//class get and set
class Movie {
 constructor(director) {
  this.dname = director;
 }
 get Mdname() {
  return this.dname;
 }
 set Mdname(x1) {
  this.dname = x1;
 }
}
movieD = new Movie("Robert Bob");
document.getElementById("getset1").innerHTML = movieD.Mdname;
this keyword

this in a method
this refers to the "owner" of the method. In above case class name Movie and function name Mdname is "owner".

//get and set underscore character
class Movie1 {
 constructor(directer) {
  this._dname = directer;
 }
 get dname() {
  return this._dname;
 }
 set dname(x2) {
  this._dname = x2;
 }
}

movieD1 = new Movie1("Ted Mosby");
document.getElementById("getset2").innerHTML =
movieD1.dname;

Don't use new Object()

  • Use {} instead of new Object()
  • Use "" instead of new String()
  • use 0 instead of new Number()
  • Use false instead of new Boolean()
  • Use [] instead of new Array()
  • Use /()/ instead of new RegExp()
  • Use function() {} instead of new Function()

 //practice
var y1 = {};  //new object
var y2 = "";  //new primitive string
var y3 = 0;   //new primitive number
var y4 = false;  //new primitive boolean
var y5 = [];  //new array object
var y6 = /()/;  //new regular expression object
var y7 = function(){};  //new function object
document.getElementById("practice").innerHTML =
"y1 is " + typeof y1 + "<br>" +
"y2 is " + typeof y2 + "<br>" +
"y3 is " + typeof y3 + "<br>" +
"y4 is " + typeof y4 + "<br>" +
"y5 is " + typeof y5 + "<br>" +
"y6 is " + typeof y6 + "<br>" +
"y7 is " + typeof y7;
 

//practice1
var x = 2;
x = 2 + 12;    // x.valueOf() is 14, typeof x is a number
var x1 = 2 + "12";  // x1.valueOf() is 212, typeof x1 is a string
var x2 = "2" + 12;  // x2.valueOf() is 212, typeof x2 is a string
var x3 = 2 - 12;    // x3.valueOf() is -10, typeof x3 is a number
var x4 = 2 - "12";  // x4.valueOf() is -10, typeof x4 is a number
var x5 = "2" - 12;  // x5.valueOf() is -10, typeof x5 is a number
var x6 = 2 - "x";  // x6.valueOf() is NaN, typeof x6 is a number

document.getElementById("practice1").innerHTML = 
x.valueOf() + " is " + typeof x + "<br>" +
x1.valueOf() + " is " + typeof x1 + "<br>" +
x2.valueOf() + " is " + typeof x2 + "<br>" +
x3.valueOf() + " is " + typeof x3 + "<br>" +
x4.valueOf() + " is " + typeof x4 + "<br>" +
x5.valueOf() + " is " + typeof x5 + "<br>" +
x6.valueOf() + " is " + typeof x6;
  

"string" minus(-) "string" become a number(NaN, Not a Number)

Comparison

//practice2
{
let x = (0 == "");
let x1 = (5 == "");
let x2 = (5 == "5");
let x3 = (0 === "0");
let x4 = (5 === "5");
let x5 = (0 == false);
let x6 = (0 ===false);
let x7 = (1 == true);
let x8 = (1 === true);

document.getElementById("practice2").innerHTML =
'(0 == "") is ' + x + "<br>" +
'(5 == "") is ' + x1 + "<br>" +
'(5 == "5") is ' + x2 + "<br>" +
'(0 === "0") is ' + x3 + "<br>" +
'(5 === "5") is ' + x4 + "<br>" +
'(0 == false) is ' + x5 + "<br>" +
'(0 === false) is ' + x6 + "<br>" +
'(1 == true) is ' + x7 + "<br>" +
'(1 === true) is ' + x8;
}
  
""の中に ""を入れてしまいerror ''で括ることで解決 variablesが他に影響しないように let で宣言

new Date().getDay() returns 0 to 6(Sunday to Saturday)

index Day
0 Sunday
1 Monday
2 Tuesday
3 Wednesday
4 Thursday
5 Friday
6 Saturday
<table>
 <tr>
  <td>index</td>
  <td>Day</td>
 </tr>
<tr>
 <td>0</td>
 <td>Sunday</td>
</tr>
<tr>
 <td>1</td>
 <td>Monday</td>
</tr>
<tr>
 <td>2</td>
 <td>Tuesday</td>
</tr>
<tr>
 <td>3</td>
 <td>Wednesday</td>
</tr>
<tr>
 <td>4</td>
 <td>Thursday</td>
</tr>
<tr>
 <td>5</td>
 <td>Friday</td>
</tr>
<tr>
 <td>6</td>
 <td>Saturday</td>
</tr>
</table>

var day;
switch (new Date().getDay()) {
 case 0:
 day = "Sunday";
 break;
 case 1:
 day = "Monday";
 break;
 case 2:
 day = "Tuesday";
 break;
 case 3:
 day = "Wednesday";
 break;
 case 4:
 day = "Thursday";
 break;
 case 5:
 day = "Friday";
 break;
 case 6:
 day = "Saturday";
 break;
 default:  //always close default: with switch.
 day = "unknown";
}
document.getElementById("tday").innerHTML = 
"Today is " + day;

Mistakes

null in JavaScript is nothing, but data type of null is object.

To test if an object does not exist, test if the type is undefined first, then check if an object is not null.

document.getElementById("").innerHTML =
typeof myObj !== "undefined" && myObj !== null;
 var person = [];
 person[0] = "Jane";
 person[1] = "Doe";
 person[2] = 46;
 var x = person.length;  //person.length will return 3
 var y =  person[0];  //person[0] will return "Jane"

 var person = [];
 person["firstName"] = "Jane";
 person["lastName"] = "Doe";
 person["age"] = 46;
 var x = person.length;  //person.length will return 0
 var y = person[0];  //person[0] will return undefined

 Objects use named index when accessing an array, JavaScript will redefine array to an object. 

 person = ["Jane", "Doe", 46]; //Array

 person = {firstName:"Jane", lastName:"Doe", age: 46}; //Object

 objectName["propertyName"]

JavaScript Reserved Words

Array Iterlation

ECMAScript 6

//ES5

var x = function(x, y){
 return x * y;
}

//ES6

const x = (x, y) => x * y;  //only if one single statement, omit the retrun keyword and curly bracket.
or
const x = (x, y) => {return x * y}; // Using const is safer than using var, because a function expression always constant value.

default parameter values

function myfunction(x, y = 10){
 // y is 10 if not passed or undefined
 return x + y; 
}
myFunction(5);  //will return 15

form validation

JavaScript form validation

HTML form attribute "required"

<input required> が優先される。


Name:

If press the "submit" button alert will show up.

<form name="mForm" onsubmit="return validationF()" method="post">
 Name: <input type="text" name="fname">
 <input type="submit" name="submit" value="Submit">
<script> 
function validationF() {
 var f1 = document.forms["mForm"]["fname"].value;
 if (f1 == "") {
  alert("Name must be filled out.");
  return false;
 }
}
</script>

.checkValidatity() method and .validationMessage;

If the number is less than 100 or greater than 300, an error message will be displayed.

function validationI() {
 const inpObj1 = document.getElementById("numI1");
 if (!inpObj1.checkValidity()) {
  document.getElementById("err1").innerHTML = 
  inpObj1.validationMessage;
 } else {
  document.getElementById("err1").innerHTML = 
  "Input is OK";
 }
} 


property validity property
validity
customError
patternMismatch
rangeOverflow
rangeUderflow
stepMismatch
tooLong
typeMismatch
valueMissing
valid

all set to true

<style>
table,th,td {
  /*border:1px solid black;*/
  border-collapse:collapse;
  text-align: left;
  padding: 8px;
 }
tr {border-bottom: 1px solid #ddd;}
tr:nth-child(even) {background-color:#f2f2f2; }
</style>

<table style="border:1px solid black;">
 <tr style="border:1px solid black;">
  <td style="border:1px solid black;">property</td>
  <td>validity property</td>
 </tr>
 <tr style="border:1px solid black;">
  <td rowspan="10">validity</td>
 </tr>
 <tr>
  <td>customError</td>

 ~~~~~~
  <tr style="border-bottom: 1px solid black;">
  <td>valid</td>
 </tr>
</table>

all set to true
 

.validity.rangeOverflow() と .validity.rangeUnderflow() は同時には無理(?)、 min max を設けて.checkValidity() methodを使えばいい分けだし。
HTML でチェックされてhover で注意が促されるし。

JavaScript if else else if

A JavaScript object is a collection of named values.

The named values, in JavaScript objects, are called property.

JavaScript objects are mutable. Any change to a copy of an object will also change the original. When Using a new keyrword(new Objectname()), it creates the same object. That's why can create/use constructor method.

constructor の練習
var person = new Object();
person.firstName ="John";
person.lastName = "Doe";
person.age =50;
person.eyeColor = "blue";

consider like below ↓
person = {firstName:"Jhon", lastName:"Doe", age:50, eyeColor:"blue"};

Object() = {firstName:"Jhon", lastName:"Doe", age:50, eyeColor:"blue"};

//constructor function
function Person(first, last, age, eye){ //  ()内はvalue
 this.firstName = first;   //this.propertyname 
 this.lastName = last;
 this.age = age;
 this.eyeColor = eye;
/*  this.name = function() { 
     return this.firstName + " has a " + this.eyeColor + " eye.";};  */
}

//Create a "new" Person object var myFather = new Person("Jhon", "Doe", 50, "blue"); //Display age document.getElementById("contsructor1").innerHTML = "My Father is " + myFather.age + "."; var myMother = new Person("Jane", "Doe", 44, "green"); document.getElementById("constructor2").innerHTML = "My Mother is " + myMother.age + "."; //add a name method to person() object myFather.name = function() { return this.firstName + " has a " + this.eyeColor + " eye."; }; try { document.getElementById("constructor3").innerHTML = myFather.name(); } catch(err) { document.getElementById("constructor3").innerHTML = err; }

To add a constructor function to a Person object
function Person(firstName, lastName, age, eyeColor) {
 this.firstName = firstName;
 this.lastName = lastName;
 this.age = age;
 this.eyeColor = eyeColor;
 this.ChangeName = function(N1) {
 this.lastName = N1;
};
}

myMother.ChangeName("Spencer");

document.getElementById("constructor4").innerHTML = 
"My mother's lastname is " + myMother.lastName;

document.getElementById("constructor5").innerHTML = 
'<span class="green">I can still access object name myMother<br> \" and \' use backslash\\ </span> <br>' + myMother.firstName + ' has a ' + myMother.eyeColor + ' eye.';

<script> 内で " double quotaion ' single quotaion は注意。どちらかで揃え \ backslash を使う。\はscriptの先頭には使わない。

HTML Entities , CSS Entities and CSS quotes property JavaScript strings



Quotaion mark and some.

∀ &forall; ← &larr; ↑ &uarr; → &rarr; ↓ &darr; HTML UTF-8 Arrows

&#8592; ←

//prototype
Person.prototype.nationality = "Belgian";
document.getElementById("prototype1").innerHTML = 
"The nationality of my father is " + myFather.nationality;

The this keyword

The thing called this is the object that 'owns' the code.
THe value of this, when used in an object, is the object itself.
In a constructor function this does not have a value. It is a substitute for a new object. The value of this wiil become the new object when a new object is created.
'this' is not a variable.

JavaScript Objects

person = {firstname:"Jane", lastname:"Doe", age:50, eyecolor:"Blue"};

ex.1
person.firstname + " is " + person.age + " years old.";

ex.2
person["firstname"] + " is " + person["age"] + " years old.";

=============

The JavaScript for in statement loops through the properties of an object. for(vaiable in object){} var txt = ""; var x = ""; for (x in person) { txt += person[x] + ""; } document.getElementById("").innerHTML = txt; ↓ Jane Doe 50 Blue

adding a new property to existing object

person.nationality = "English";
document.getElementById("").innerHTML = 
person.firstname + " is " + person.nationality + ".";
↓
Jane is English.

//Object Method and function
var person = {firstname:"Jane", lastname:"Doe", age:50, id:4432,
fullname: function() {
 return this.firstname + " " + this.lastname;
}
};  //semicolon

document.getElementById("ObjM1").innerHTML =
person.fullname();

document.getElementById("ObjM2").innerHTML =
person.fullname;
document.getElementById("ObjM1").innerHTML =
person.fullname();
↓

document.getElementById("ObjM2").innerHTML =
person.fullname;
↓

Adding a method to an object

//adding a method to an object
{
 let ted = {firstname:"Ted", lastname:"Mosby", job:"architect"};
 ted.name = function() {
  return this.firstname + " " + this.lastname + " :The " + this.job;
 };
 document.getElementById("ObjM3").innerHTML =
 ted.name();
}

JavaScript function or getter?
get を使ったほうが文法が少し簡単になる(でも慣れの問題?)。()を忘れても成立する。文法もシンプルなfunction() 宣言declareのようになる。

{
 let ted = {firstname:"Ted", lastname:"Mosby", job:"architect",
 get fullname() {
 return this.firstname + " " + this.lastname + " The: " + this.job;
}
};
document.getElementById("ObjM4").innerHTML =
ted.fullname;
}

ES5 new object methods

Object.defineProperty(object, property, descriptor)
//Adding or changing an object proprety
Object.defineProperties(object, descriptors)
//Adding or changing many object properties

Prototype Inheritance

All javaScript objects inherit properties and methods from a prototype:

  • Date objects inherit from Date.prototype
  • Array objects inherit from Array.prototype
  • Person objects inherit from Person.prototype

JavaScript Prototype, reserved words

Object.defineProperty(object, property, descriptor)

Objet.getOwnPropertyNames(Person) ↓

prototype, language, name は予想できたがlengthは何処からやってきた?

CSS 
<style>
backgroud-color: lightblue;
background-image: linear-gradient(rgba(255, 255, 255, 0.8),rgba(255, 255, 255, 0.3));
</style>

Object.getOwnPropertyNames(person) ↓

adding object names of person to {language; "Chinese"} ↓ default value
fullname is function

Find Object "person"

document.getElementById("OdP3").innerHTML =
Person.prototype.nationality + " , " + Person.language + " , " + Person.length + " , " + Person.name;
↓

Person.length returns 4

Find Object "Person"
//Returns enumerable properties as an array
Object.keys(object)
やっていることはloop through 
for(vaiable in object){}
ここと同じ


try {
 document.getElementById("Okeys1").innerHTML = Object.keys(myMother);
} catch(err) {
document.getElementById("Okeys1").innerHTML = err;
} 
↓

document.getElementById("accessPrototype").innerHTML = Object.getPrototypeOf(myMother);
↓

document.getElementById("PtoS1").innerHTML =
Object.prototype.valueOf(Person);
↓

Function

variables can be used as a function, if function has been stored in variables.

{
 let x = function (a, b, c) {return a*b-c+a};
 document.getElementById("storedCan").innerHTML = x(5, 9, 3);
}
↓

a function with arguments
callFunc("Harry Potter", "Wizard")

//function with arguments
function callFunc(name, job){
 document.getElementById("harry").innerHTML =
 "Welcome " + name + ", the " + job +".";
}

//self-invoke
Function expressions will execute automatically if the expression is followed by ()
adding parentheses around the function to indicate that it is a function expression.
(function(){
 document.getElementById("selfI").innerHTML =
 "HELLO! I called myself";
}) ();

A function defined as the property of an object, is called a method to the object.
Afunction designed to create new objects, is called an object constructor.

arguments.length
arguments.length property returns the number of arguments received by the function:

function myFunction(a, b, c){
 return arguments.length;
}
document.getElementById("ALmethod").innerHTML = myFunction(100, 50, -88);
↓

Finding the largest number

findMaxFunc(1, 123, 345, 456, 567, 80, -30); ↓

function findMaxFunc() {
 var i;
 var max = -Infinity;  // negative Infinity無し だとerror.
  positive Infinityだと そのままInfinity まで探しに行ってしまってreturn するのはInfinity
 for(i=0; i < arguments.length; i++) {
  if(arguments[i] > max) {
   max = arguments[i];
  }
 }
 return max;
}

document.getElementById("findMax").innerHTML =
findMaxFunc(1, 123, 345, 456, 567, 80, -30);
↓

+= arguments[i]

function myFunctionS() {
 var i;
 var sum = 0; //sum =0;がないとwhite space error.
  "0" という起点がないと += が生きない

 for (i = 0; i < arguments.length; i++){
  sum += arguments[i] ;
 }
  return sum;
}
document.getElementById("sum1").innerHTML = myFunctionS(1, 123, 345, 456, 567, 80, -30);
↓

//function constructor
function CFunction(argu1, argu2, argu3){
 this.firstName = argu1;
 this.lastName = argu2;
 this.nationality = argu3;
}

// creating a new object
var con1 = new CFunction("Barney", "Stinson", "Belgium")
document.getElementById("construct1").innerHTML =con1.firstName + " from " + con1.nationality;

HTML DOM(Document Object Model)

getElementsByTagName("p") x[2].innerHTML↓

<table> の中の<td> を探してもらおうとするが失敗。
querySelectorAll("") ならうまく行った querySelectorAll("pre.source") x[2]

The DOM is very useful.

getElementsByTagName not getElementById small s is neccessary.

getElementsByTagName("p")[0].innerHTML = ;
tag name"p" of the first element

Changing the value of attribute
document.getElementById("idname").attribute = new value

document.getElementById("").src = "url";

flexbox のcolumn 配置

  style="display: flex;
   flex-direction: column; 
   box-shadow: 0 4px 8px 0 rgba(2, 3, 0, 0.5),0 8px 3px 0 rgba(4, 3, 0, 0.2);
   width:140px;"
 =======
 <div style="padding: 5px;">
    <img width="130px" >
    =======
    <div style="padding: 5px; text-align: center;"
 

HTML DOM Style object, HTML DOM Style Flex Direction

JavaScript First name:
Last name:

HTML forms <fieldset> <legend>
HTML input attributes disabled attribute

animation

function clickA() {
 var elem =
 document.getElementById("Animate1");
 var pos = 0;
 var id = setInterval(frame, 50);
 function frame() {
  if (pos == 100) {
   clearInterval(id);
  } else {
   pos++;
   elem.style.left = pos + "%";
   elem.style.right = pos + "%";
  }
 }
}
function clickB() {
 var elem = 
 document.getElementById("AN2");
 var pos = 0;
 var id = setInterval(frame1, 50);
 function frame1() {
  do  {
   pos++;
   elem.style.left = pos + "px";
   elem.style.right = pos +"px";
  } while (pos === 300);
 }

click and load Time Now!

<p> <button> どちらをclickしても Date()が動く。

Mouse Over Here
click here

コメント

このブログの人気の投稿

スタートアップフォルダとAmatsukazeのエンコード設定

EDCB Recname_MacroのRMで文字削除がうまく行かない

冠山トンネル周辺のライブカメラ