MW Portfolio HTML CSS JavaScript Splunk Kafka DDIA
JS

JS

variables type

Value Reference
primitive type is assigned to a variable passed by reference
we can think of that variable as containing the primitive value. Variables that are assigned a non-primitive value are given a reference to that value. That reference points to the object’s location in memory. The variables don’t actually contain the value.
var a = 100
var b = a 
a = 200
console.log(b)  //100
//we can think of that variable as containing the primitive value.  

var a = {age:20}
var b = a
b.age = 21
console.log(a.age) //21
//The variables don’t actually contain the value.
See this one

Typeof

// some examples
typeof undefined // undefined
typeof 'abc' //string
typeof 123 //number
typeof true //boolean
typeof {} // object
typeof [] // object
typeof null // object
typeof console.log // function
typeof NaN                    // Returns "number"
typeof new Date()             // Returns "object"
typeof function () {}         // Returns "function"
typeof myCar                  // Returns "undefined" 

type caculation ---- type conversion

String concat: numer to string and then concat.

// number to string
var b = 100.66 + '88' // '100.6688'

== operator

100 == '100' //true
0 == '' // true
null == undefined //true
1 == '1'; // true
1 == [1]; // true
1 == true; // true
0 == ''; // true
0 == '0'; // true
0 == false; // true

logical operator

console.log(10 && 0)  // 0
console.log('' || 'abc')  // 'abc'
console.log(!window.abc)  // true

// identify true or false of a variable
var a = 100 
console.log(!!a)  //true

JSON

// JSON is a object in javascript
// object to string
JSON.stringify({a:10, b:20})
// string to object
JSON.parse('{"a":10, "b":20}')

symbol

var s = Symbol()
typeof s
//"symbol"

Type Conversion Table

Original Value Converted to Number Converted to String Converted to Boolean
false 0 "false" false
true 1 "true" true
0 0 "0" false
1 1 "1" true
"0" 0 "0" true
"000" 0 "000" true
"1" 1 "1" true
NaN NaN "NaN" false
Infinity Infinity "Infinity" true
-Infinity -Infinity "-Infinity" true
"" 0 "" false
"20" 20 "20" true
"twenty" NaN "twenty" true
[] 0 "" true
[20] 20 "20" true
[10, 20] NaN "10, 20" true
["twenty"] NaN "twenty" true
["ten", "twenty"] NaN "ten, twenty" true
function(){} NaN "function(){}" true
{ } NaN "[object Object]" true
null 0 "null" false
undefined NaN "undefined" false

Prototype and Prototype Chain

constructor function

function Foo(){
  this.name = name
  this.age = age
  this.class = 'class-1'
  // return this // default have this line
}

var f = new Foo('zhangsan', 20)
  • var a = {} is a syntax sugar of var a = new Object()
  • var a = [] is a syntax sugar of var a = new Array()
  • function Foo(){...} is a sytax sugar of var Foo = new Function(...)
  • using instanceof to identify whether a function is functiion.

Rules of prototype

  • All reference type(array, object, function) have the property of object, what is it can be extened.(except null)
  • All reference type(array, object, function) have a __proto__ property, which is a object.
  • All functions have a prototype property, which is a object
  • obj.__proto__ === Object.prototype.
  • will search in __proto__

Closure

A closure is the combination of a function and the lexical environment within which that function was declared.

function makeAdder(x) {
  return function(y) {
    return x + y;
  };
}

var add5 = makeAdder(5);
var add10 = makeAdder(10);

console.log(add5(2));  // 7
console.log(add10(2)); // 12
// this is a window
var name = "The Window";
var object = {
  name : "My Object",
  getNameFunc : function(){
    return function(){
      return this.name;
    };
  }
};
alert(object.getNameFunc()());
// how to fix
var name = "The Window";
var object = {
  name : "My Object",
  getNameFunc : function(){
    var that = this;
    return function(){
      return that.name;
    };
  }
};

alert(object.getNameFunc()());

Asynchronous

DOM

Event

Ajax

Write Ajax without third-party libaries

Ajax cross domain

Same-origin policy

This is a security policy who defines the rules of how a web page can access an external resource (e.g. fonts, AJAX requests). Under the same-origin policy, web browsers do not permit a web page to access resources who origin differ than that of the current page. The origin is considered to be different when the scheme, hostname or port of the resource do not match that of the page. Overcoming the limitations of same-origin security policy is possible using a technique called Cross-origin resource sharing or simply CORS.

Situations of cross domain

Same-origin policy permits scripts running on pages originating from the same site to access each other's data with no specific restrictions, but prevents scripts access to data that is stored on a different domain.

Different in Protocol, domain and port

How to resolve it?

  • Implement CORS (Cross-Origin Resource Sharing)
  • Use JSONP (JSON Padding)
  • Use postMessage method
  • Setting up a local proxy

Solutions in detail

How to use it outside domain

Three tags which can load data cross domain

  • img
  • link
  • script

Storage

Promise

Basic syntax of promise

//Basic syntax of promise
function loadImg(src) {
  const promise = new Promise(function(resolve, reject) {
    var img = document.createElement('img')
    img.onload = function () {
      resolve(img)
    }
    img.onerror = function () {
      reject()
    }
    img.src = src
  })
  return promise
}

var src = 'https://www.imooc.com/static/img/index/logo.png'
var result = loadImg(src)
result.then(function(img){
  console.log(img.width)
}, function () {
  console.log('failed')
}).then(function(img){
  console.log(img.height)

})
        

Exception catch

//Exception catch
result.then(function (img) {
  console.log(1, img.width)
  return img
}).then(
  console.log(2, img.heigth)
).catch(function() {
  console.log(ex)
})
        

Use promise in sequence

//Use promise in sequence
var src1 = 'https://www.imooc.com/static/img/index/logo.png'
var result1 = loadImg(src1)
var src2 = 'https://img2.mukewang.com/5a9fc8070001a82402060220-160-160.jpg'
var result2 = loadImg(src2)

result1.then(function () {
  console.log('Finished the first image')
  return result2
}).then(function () {
  console.log('Finished the second image')  
}).catch(function (ex) {
  console.log(ex)
})
        

Promise.all & Promise.race

//Promise.all & Promise.race
// Promise.all finish all and then return success
Promise.all([result1, result2]).then(datas => {
    console.log(datas[0])
    console.log(datas[1])
})

//Promise.race finish one and return success
Promise.race([result1, result2]).then(data => {
    console.log(data)
})     
More Promise explain

Async/Await

Write similar to sync

//Async/Sync
const load = async function () {
  cosnt result1 = await loadImg(src1)
  console.log(result1)
  const result2 = await loadImg(src2)
  console.log(result2)
}
load()  
  • If you want to await, function must be identified by async
  • Await is followed by a Promise
  • Need babel-polyfill

Questions ( js, html, css )

1. The Document Object Model (DOM) is an application programming interface (API) for HTML and XML documents.
2. It defines the logical structure of documents and the way a document is accessed and manipulated.
3. The DOM represents the document as nodes and objects. programs can change the document structure, style, and content.
4. That way, programming languages can connect to the page.

When an event triggers on a DOM element, that event does not only occur on that just one element. It has event propagation. There are two ways of event propagation --- event bubbling and event caputering.

When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.Until to the Windows

In Capturing Phase, the event starts from the window all the way down to the element that triggered the event.then it reaches the target and triggers there (target phase), and then it goes up (bubbling phase), calling handlers on its way. capturing phase is rarely used. Normally it is invisible to us.

// true as tired parameter
 addEvent(child, 'click', function (e) {
    console.log('child');
  }, true);   

1. if we have a lot of elements handled in a similar way, then instead of assigning a handler to each of them – we put a single handler on their common ancestor.
2. In the handler we get event.target, see where the event actually happened and handle it.


// Get the element, add a click listener...
document.getElementById("parent-list").addEventListener("click", function(e) {
  // e.target is the clicked element!
  // If it was a list item
  if(e.target && e.target.nodeName == "LI") {
    // List item found!  Output the ID!
    console.log("List item ", e.target.id.replace("post-", ""), " was clicked!");
  }
});     

1. e.preventDefault() prevents the default action the browser makes on that event. If used in a form element it prevents it from submitting. If used in an anchor element it prevents it from navigating.
2. e.stopPropagation() stops the propogation of an event or it stops the event from occurring in the bubbling or capturing phase.

We can use the event.defaultPrevented property in the event object. It returns a boolean indicating if the event.preventDefault() was called in a particular element.

// if statement
if (event.defaultPrevented) {
      log.innerText = 'Sorry, but you cannot visit this link!\n' + log.innerText;
}    

The target property of the Event interface is a reference to element that event is trigered. It is different from Event.currentTarget when the event handler is called during the bubbling or capturing phase of the event.

The currentTarget read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred and which may be its descendant. whole 'ul'

Hoisting is a javascript mechanism where variables and function declarations are moved to the top of their scope before code excution

When an event triggers on a DOM element, it will attempt to handle the event if there is a listener attached, then the event is bubbled up to its parent and the same thing happens. This bubbling occurs up the element's ancestors all the way to the document. Event bubbling is the mechanism behind event delegation.

1. A closure is an inner function that has access to the outer function's variables.
2. The closure has three scope chains: it has access to its own scope , it has access to the outer function's variables, and it has access to the global variables.

// name can be alert
function init() {
  var name = 'Mozilla'; // name is a local variable created by init
  function displayName() { // displayName() is the inner function, a closure
    alert(name); // use variable declared in the parent function
  }
  displayName();
}
init();   

1. 'Strict mode' means more strict than Javascript normal mode,and you can insert 'use strict ' statement on the top of your script.
2. 'strict mode' can gives you benefit. for example:
a. without strict mode, a reference to this value of null or undefined is automatically is bind to global. which could cause some hidden bug there. but if you use strict mode, the reference to this value will throw an error if you are trying to do like null or undefined.
b. 'strict mode' don’t allow to use a variable without declaring it.
c. you can not use the 'with' statement in strict mode.
d. Duplicating a parameter name is not allowed.
e. Deleting an undeletable property is not allowed.
f. Assigning a value to a read-only or non-writable global variable;

1. LocalStorage is local storage for your browsers, it can save up to 10MB.· it will exist for long time until you delete it
2. SessionStorage is session based and will be deleted after closing your tab, also can save less than LocalStorage, like up to 5MB
3. Cookies are very tiny data storing in your browser, that can save up 4KB. server & browser can both use cookie.

1. HTML is short for Hypertext Markup Language.
2. HTML is used to tell your browser how to structure the web page.
3. HTML consists of a series of elements, which are the building block of the html pages.

1. Add new semantic elements, it good for SEO and web accessibility. Such as nav article
2. Add new form input type, such as color number email
3. Add Muli-Media elements such as video audio canvas
4. support web storage such as session storage local storage

1. an inline element: 1. never adds a new line after it. 2. ignores margin-top and margin-bottom settings. 3. ignores width and height properties. 4. is subject to vertical-align properties
2. a block-level element: 1. starts and ends on a new line. 2. takes up the full width of its parent element. 3. is subject to margin, padding, height, width, etc. 4. can take up more than one line 5. ignores vertical-align property

1. Use correct semantic tag. like <'main'> <'article'> <'header'> 2. make sure all the images have "alt" text. 3. building keyboard accessiblity, like using "tabindex" attribute on tags which defines the navigation order for focusable elements within a page. It can also be used to define whether elements should be focusable or not. 4. In a table, using 'th' and 'caption>'tags. 5. use <'button'> tag instead of<'div'> tag if you need. because <'button'> tag have built-in keyboard accessibility. 6. ARIA(Assistive Rich Internet Applications) can improve accessibility of web pages and applications by providing extra information to screen readers via HTML attributes

SVG stands for Scalable Vector Graphics SVG is used to define graphics for the Web SVG is a W3C recommendation SVG is a document format for scalable vector graphics.
Canvas is a javascript API for drawing vector graphics to a bitmap of a specific size.
To elaborate a bit, on format versus API:
With svg you can view, save and edit the file in many different tools. With canvas you just draw, and nothing is retained about what you just did apart from the resulting image on the screen. You can animate both, SVG handles the redrawing for you by just looking at the elements and attributes specified, while with canvas you have to redraw each frame yourself using the API. You can scale both, but SVG does it automatically, while with canvas again, you have to re-issue the drawing commands for the given size.

 pseudo-class describe a special state. it allow to style element dynamically. The most popular one is :hover.

pseudo-element match virtual elements. it used to style specified parts of an element. we often use like " ::after ::before ::first-line".

1. space descendant selector
2. > child selector
3. + adjacent sibling selector
4. ~ general sibling selector

css box model is a box that wraps around every html element, box model includes the content, padding, border and margin. so it have 2 types of box model which are content-box and border-box, we can use "box-sizing" this property to define which box model you will use.
使用margin的情况:
1. 需要在border外侧添加空白时。
2. 空白处不需要背景(色)时。
3. 上下相连的两个盒子之间的空白,需要相互抵消时。如15px + 20px的margin,将得到20px的空白。
使用padding的情况:
1. 需要在border内测添加空白时。
2. 空白处需要背景(色)时。
3. 上下相连的两个盒子之间的空白,希望等于两者之和时。如15px + 20px的padding,将得到35px的空白。

1. First, I often define flex container and flex aitems.
2. then use "display: flex" on that flex container.
3. use "justify-content" to define the horizontal alignment of items. "justify-content" have values: flex-start, flex-end, start, center,end, space-between, space-around, space-evenly;
4. use"align-items" to define the vertical alignment of items.
5. If my main-axis is vertical , I can set "flex-direction: column" .
6. for children item, I can use "order", "flex-grow", "flex-basis", "align-self" to adjust content.

1. float is a CSS positioning property. float value have: none, left, right, initial.
2. float pushes an element to the sides of a page with text wrapped around it.
3. we can create entire page or a smaller area by using float. if size of a floated element changes, text around it will re-flow to accommodate the changes.
4. if we set, 'float: left;' for an image, it will move to the left until the margin, padding or border of another block-level element is reached. The normal flow will wrap around on the right side.

1. fixed: relative to browser, which means it always stays in the same place even if the page is scrolled.
2. relative: relative to it's original(normal) position
3. absolute: relative to its non-static parent, if can't find, it will relative to the browser. It will find the most closed parents element that is non-static. Absolute positioned elements are removed from the normal flow, which means it can be overlapped by other elements.
4. static: default value. Elements render in order, as they appear in the document flow. Not affected by the top, bottom, left, right and z-index properties. Other content will not be adjusted to fit into any gap left by the element.
5. sticky: An element with position: sticky; is positioned based on the user's scroll position. A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position:fixed).

Specificity means a browser decides which property values are the most relevant to an element and gets to be applied. CSS styles follow an order of specificity. It specifies when styles override another or take precedence.
1. Inline css is higher than style tag 2. style tag is higher than css introduced by the tag 3. Id selector is higher than class and then higher than tag name 4. Tow color properties in the same curly brakets, the later one will override the previous one. 5. You can use "!important" statement to make the highest priority specificity. 6. Inherited css has the lowest priority.(Inherited property uses the property value from its parent property)
Inline style > id > class == Attribute == pseudo class > simple element

wapper: grid-template-rows, grid-template-columns item: grid-column-start, end grid-row-start, end

Generally, there are 3 problems that CSS naming conventions try to solve: 1. To know what a selector does, just by looking at its name 2. To have an idea of where a selector can be used, just by looking at it 3. To know the relationships between class names, just by looking at them
What's BEM? 1. BEM is short for block element modifier, B is 'block', E is 'element', M is 'modifer'.
2. BEM is a front end methodology, it have several benefits ,like, BEM is open to change, simple for teams to follow., and it can create efficient and organised CSS. you can transfer blocks between projects
3. for example, if you got a list, the whole list can be treated as block, and each of list can be element, if you want put different style on the each element, you can write the modifer style css selector to achieve it. which have shows the clear relationship between element and block.

1. What's Sass? ○ Sass is short for "Syntactically Awesome Style Sheets". ○ Sass is an extension of CSS that allow you to use things like variables, nested rules, inline imports and more. it also helps to keep things organised and allows you to create style sheets faster. 2. core feature of Saas? ○ Variables ○ Nesting ○ Import ○ Partials ○ Mixins: § mixin is like CSS functions. § I use mixins to define a block, inside that block, I can wirte any re-suable style. which it can make my sass code more short and clean. § This will provide more reusability. ○ Operators ○ Extend/Inheritance